json
JSON 序列化 / 反序列化。
类型映射(双向):
| Lua | JSON |
|---|---|
nil | null |
bool | bool |
number | number(整数走 int 路径) |
string | string |
连续 1..N 数字索引 table | array |
| 其他 table | object |
| function / userdata | (跳过 + LOG_WARN) |
json.encode(value, pretty?) → string
参数:
value : any— 待序列化值pretty? : bool = false— true 用 2-space 缩进,便于人读
序列化失败(极少,仅类型不可恢复时)返回 "null"。
json.decode(text) → value | nil, err_msg
参数:text : string
返回:成功时返单个 Lua 值;失败时返 (nil, error_string),调用方用 if v == nil then ... 判断。
Lua 接收
1..N连续整数 key 的 table = JSON array;其他 key 形态 = JSON object。空 table{}默认编码为"[]"(视为空数组),需要空对象时手动加任意 string key 触发非数组判定。
示例
lua
-- encode
local cfg = {
name = "alice",
age = 30,
tags = { "admin", "user" },
pos = { x = 1.5, y = 2.5 },
on = true,
}
local text = json.encode(cfg)
file.write("conf/my_state.json", text)
-- decode + 错误处理
local raw = file.read("conf/my_state.json") or ""
local loaded, err = json.decode(raw)
if not loaded then
log.warn("配置 parse 失败:" .. err)
loaded = { age = 0 } -- 兜底
end
print(loaded.name)适合配合 net.http 做远端配置推送:
lua
net.http:post("https://api.example.com/save",
json.encode({ event = "session_start" }),
"application/json",
function(resp)
local body, err = json.decode(resp.body or "")
if body and body.ok then
gui.notify:success("已上报")
end
end, 5)