coloX cjson JSON 编解码模块 Lua 编程指南
cjson 是高性能 JSON 编解码模块(C 实现),用于与 HTTP API、WebSocket 消息、配置数据等 JSON 内容互转。
启用方式
模块随宿主预载,require 后即可使用,无需 usemod:
local json = require("cjson") -- 标准版(出错抛 Lua 错误)
local json = require("cjson_safe") -- 安全版(出错返回 nil, err)
目录
1. 核心概念:类型映射
Lua → JSON(encode)
| Lua 值 | JSON 结果 |
|---|---|
| table(键为连续整数 1..n) | 数组 [...] |
| table(其他键型/混合) | 对象 {...}(键 tostring 后输出) |
空表 {} | 对象 {}(不是数组 []) |
| string | 字符串(转义 " \ 控制字符等) |
| number | 数字(整数直接输出;浮点按精度设置,见 §3) |
| boolean | true / false |
json.null(哨兵,见 §2) | null |
| NaN / Infinity | 默认报错(可配置,见 §3) |
| function / userdata / thread | 报错 |
JSON → Lua(decode)
| JSON 值 | Lua 结果 |
|---|---|
| object | table(键为字符串) |
| array | table(1 基数组) |
| string | string(UTF-8 原样保留) |
| number | number(整数样式的值尽量解码为整数;浮点受平台 32 位浮点精度限制,约 7 位有效数字) |
true / false | boolean |
null | json.null 哨兵(lightuserdata;因为 Lua 的 nil 无法存入 table) |
对象的重复键后者覆盖前者。深嵌套结构受
decode_max_depth限制(默认 1000 层)。
平台数值为 32 位(整数 int32、浮点 float32):超大整数(超出 ±2^31)与高精度小数会损失精度,需要精确传递时用字符串承载。
2. API 详解
json.encode(obj) → string
把 Lua 值编码为 JSON 字符串。出错(非法类型、超深度、NaN/Infinity 等)抛 Lua 错误。
local json = require("cjson")
json.encode({ name = "coloX", tags = {"game", "demo"}, score = 99.5 })
-- → '{"name":"coloX","tags":["game","demo"],"score":99.5}'
json.decode(str) → value
解析 JSON 字符串为 Lua 值。出错抛 Lua 错误(需要不抛错的版本见 §4)。
local obj = json.decode('{"user":{"name":"小明","age":18},"active":true}')
print(obj.user.name) -- 小明
print(obj.active) -- true
json.null — null 哨兵
json.null 是一个 lightuserdata 哨兵值,用于在 Lua 侧表达 JSON 的 null(区别于"字段不存在"):
local obj = json.decode('{"a":null}')
print(obj.a) -- userdata: 0x0 (json.null,不是 nil)
print(obj.a == json.null) -- true
print(obj.b) -- nil(字段不存在)
-- 编码时塞回 null
obj.a = json.null
json.encode(obj) -- '{"a":null}'
判断"值为 null"与"字段缺失":
if obj.a == nil then -- 字段不存在
elseif obj.a == json.null then -- 值为 null
end
json.new() → module
创建一个独立配置的新模块实例——对它调用 §3 的配置函数不影响 require("cjson") 的全局配置。
local myjson = json.new()
myjson.encode_max_depth(20) -- 只影响 myjson
3. 配置项
所有配置函数三态:不传参数 = 查询(返回当前值);传参数 = 设置(返回旧值)。
| 函数 | 默认 | 说明 |
|---|---|---|
encode_sparse_array(convert [, ratio [, safe]]) | 0, 2, 10 | 稀疏数组处理:convert=0(默认)时,数组空洞按 ratio/safe 策略处理(小空洞补 null,过大转对象);convert=1 稀疏表一律编码为对象 |
encode_max_depth(depth) | 1000 | 编码最大嵌套深度,超出报错 |
decode_max_depth(depth) | 1000 | 解码最大嵌套深度,超出报错 |
encode_number_precision(precision) | 14 | 浮点编码有效数字,1-14(平台浮点 32 位,超过 7 位的设置无实际收益) |
encode_keep_buffer(enabled) | true | 复用内部编码缓冲区(省内存时关掉) |
encode_invalid_numbers(mode) | "off" | NaN/Infinity 编码策略:"off" 报错 / "on" 输出 NaN、Infinity 字面量 / "null" 输出 null |
decode_invalid_numbers(enabled) | true | 是否接受 NaN/Infinity 字面量(非严格 JSON) |
local json = require("cjson")
json.decode_max_depth(64) -- 限制深度防恶意 JSON
json.encode_invalid_numbers("null") -- NaN → null
local old = json.encode_max_depth() -- 查询当前值
4. cjson_safe
cjson_safe 的 API 与 cjson 完全一致,区别是 encode/decode 出错时返回 nil, err 而不是抛异常,适合处理外部输入(网络响应等)不想 pcall 的场景:
local json = require("cjson_safe")
local obj, err = json.decode('{"broken": ...')
if not obj then
printh("JSON parse failed: " .. tostring(err))
end
5. 综合示例
解析 HTTP API 的 JSON 响应
配合 net 模块(见 net.md):
usemod('net')
#include colox_net.lua
#include colox_http.lua
local json = require("cjson_safe")
copas.addthread(function()
local body, code = nethttp.request("https://api.example.com/v1/data")
if not body or code ~= 200 then
printh("request failed")
return
end
local data, err = json.decode(body)
if not data then
printh("bad json: " .. tostring(err))
return
end
for _, item in ipairs(data.list or {}) do
printh(item.id .. ": " .. tostring(item.name))
end
end)
function _draw() copas.step() end
用 string.pack 组二进制协议 + JSON 文本混合帧
(string.pack 见 lua.md 标准库一节)
local json = require("cjson")
-- 帧格式: 2字节长度 + JSON 文本
local payload = json.encode({ cmd = "move", x = 12, y = 34 })
local frame = string.pack("<I2", #payload) .. payload
-- 解帧
local len = string.unpack("<I2", frame)
local msg = json.decode(string.sub(frame, 3, 2 + len))
6. 完整 API 索引
| 函数/字段 | 返回 | 说明 |
|---|---|---|
require("cjson") | module | 标准版模块(出错抛错) |
require("cjson_safe") | module | 安全版模块(出错返回 nil, err) |
json.encode(obj) | string | 编码 |
json.decode(str) | value | 解码 |
json.null | lightuserdata | null 哨兵(判等用) |
json.new() | module | 独立配置新实例 |
json.encode_sparse_array(...) | 旧值/当前值 | 稀疏数组策略 |
json.encode_max_depth([n]) | 旧值/当前值 | 编码深度限制(默认 1000) |
json.decode_max_depth([n]) | 旧值/当前值 | 解码深度限制(默认 1000) |
json.encode_number_precision([n]) | 旧值/当前值 | 浮点有效数字(1-14) |
json.encode_keep_buffer([b]) | 旧值/当前值 | 编码缓冲复用(默认 true) |
json.encode_invalid_numbers([m]) | 旧值/当前值 | NaN/Inf 策略("off"/"on"/"null") |
json.decode_invalid_numbers([b]) | 旧值/当前值 | 接受 NaN/Inf 字面量(默认 true) |
json._NAME / json._VERSION | string | 模块名/版本 |