08-其他库
6.2.3 其他库
除了标准库以外,Redis还通过cjson库6和cmsgpack库7提供了对JSON和MessagePack的支持。Redis自动加载了这两个库,在脚本中可以分别通过 cjson 和 cmsgpack 两个全局变量来访问对应的库。两者的用法如下:
6 http://www.kyne.com.au/~mark/software/lua-cjson.php
7 cmsgpack库的作者正是Redis的作者Salvatore Sanfilippo,其项目地址是https://github.com/antirez/lua-cmsgpack。
local people = {
name = 'Bob',
age = 29
}
-- 使用cjson序列化成字符串:
local json_people_str = cjson.encode(people)
-- 使用cmsgpack序列化成字符串:
local msgpack_people_str = cmsgpack.pack(people)
-- 使用cjson将序列化后的字符串还原成表:
local json_people_obj = cjson.decode(people)
print(json_people_obj.name)
-- 使用cmsgpack将序列化后的字符串还原成表:
local msgpack_people_obj = cmsgpack.unpack(people)
print(msgpack_people_obj.name)