a-cjson API 调用完成 Lua 值与 Json 值的相互转换(编码及解码)。
注:lua-cjson 哀求编码格式为UTF8。lua-cjson 不支持 UTF-16 and UTF-32。
Step 1:安装 Lua 环境:

上传 Lua 源码 lua-5.3.5.tar.gz 到用户主目录($HOME)下,解压缩,得到 lua-5.3.5 目录。
修正 $HOME/lua-5.3.5/Makefile 文件:
编译 && 安装:
安装完毕:
Step 2:安装 lua-cjson 库:
上传 lua-cjson 源码 lua-cjson-2.1.0.tar.gz 到用户主目录($HOME)下,解压缩,得到 lua-cjson-2.1.0 目录。
修正 $HOME/lua-cjson-2.1.0/Makefile 文件:
编译 && 安装:
安装完毕:
实行 lua 脚本:
实行 lua 脚本:
注:
1)LUA_CPATH=$HOME/lua/lib/lua/5.1/?.so lua
将 LUA_CPATH 作为环境变量传入 lua 进程环境表,以便 lua 在实行 require 函数时可以知道从哪里 dlopen 这个动态库。
当然,没必要一定写到命令行中,完备可以写到 $HOME/.bash_profile 中,export LUA_CPATH。
上面的示例代码中利用了两个 API:cjson.encode and cjson.decode。
cjson.encode 是用于编码,将 lua 值转换为 json 字符串; cjson.decode 是用于解码,将 json 字符串转换为 lua 值;
除了这两个 API,还有以下 API 可以利用:
上面的示例中也有利用到 new 接口:
可以通过 new 接口创建一个 cjson 实例工具,此工具含有独立的编解码缓冲区以及独立的配置参数表。
如果多个线程同时对同一个 cjson 实例工具调用编解码操作,结果是不可预估的。
由于多个线程实质上对同时对同一编解码缓冲区进行了读写操作。
以是,不同线程应该串行操作同一个 cjson 实例工具 或 并行操作互不相同的 cjson 实例工具(不同的编解码缓冲区)。
Lua CJSON can support Lua implementations using multiple preemptive threads within a single Lua state provided the persistent encoding buffer is not shared.
This can be achieved by one of the following methods:
Disabling the persistent encoding buffer with cjson.encode_keep_buffer
Ensuring each thread calls cjson.encode separately (ie, treat cjson.encode as non-reentrant).
Using a separate cjson module table per preemptive thread (cjson.new)
lua-cjson 供应一些 API 以修正 cjson 实例工具的参数表默认配置,来影响 cjson 实例工具在编码解码时的行为过程。
例如,可以通过 encode_max_depth 和 decode_max_depth 来变动编解码时的最大嵌套深度,等等。
关于 lua-cjson cjson.encode 序列化 Lua 值的一点问题
实行结果为:
当存在某 key-value 对且 key 类型不是 number 类型:
实行结果为:
缘故原由在于:
Lua CJSON uses a heuristic to determine whether to encode a Lua table as a JSON array or an object.
A Lua table with only positive integer keys of type number will be encoded as a JSON array.
All other tables will be encoded as a JSON object.
其余,cjson.encode 不会触发元方法:
Lua CJSON does not use metamethods when serialising tables.
rawget is used to iterate over Lua arrays
next is used to iterate over Lua objects
以及,若待转换的 Lua table 中的 key 有非 number 且非 string 类型值,则转换时报错:
JSON object keys are always strings.
Hence cjson.encode only supports table keys which are type number or string.
All other types will generate an error.
在 cjson.encode 时,由于待转换 Lua table 不符合转换哀求可能引发一些缺点:
By default, encoding the following Lua values will generate errors:
Numbers incompatible with the JSON specification (infinity, NaN)
Tables nested more than 1000 levels deep
Excessively sparse Lua arrays
我们可以通过一些 lua-cjson 供应的 API,修正 cjson 实例工具默认参数值,使得在 encode 时行为改变:
cjson.encode_invalid_numbers
cjson.encode_max_depth
cjson.encode_sparse_array
1.https://www.kyne.com.au/~mark/software/lua-cjson-manual.html#encode_max_depth
1.https://www.kyne.com.au/~mark/software/download/lua-cjson-2.1.0.tar.gz
2.https://www.kyne.com.au/~mark/software/lua-cjson.php
3.https://github.com/mpx/lua-cjson/