jokymouse.json API
jokymouse.json 模块通过 require("jokymouse.json") 加载,提供 Lua 与 JSON 之间的序列化与反序列化能力。
local json = require("jokymouse.json")
可用函数
| 函数 | 签名 | 说明 |
|---|
| encode | json.encode(value) | Lua 值 → JSON 字符串(紧凑格式) |
| encode_pretty | json.encode_pretty(value) | Lua 值 → JSON 字符串(缩进格式) |
| decode | json.decode(str) | JSON 字符串 → Lua 值 |
encode
local json = require("jokymouse.json")
local str = json.encode({ action = "buy", count = 3, tags = { "hot", "new" } })
print(str)
类型映射
| Lua 类型 | JSON 类型 |
|---|
nil | null |
boolean | true / false |
integer | number(整数) |
number | number(浮点);NaN / Infinity 会抛出错误 |
string | string |
| table(数组) | array(key 为连续正整数 1..n) |
| table(对象) | object(其他情况) |
| 其他类型 | 抛出错误 |
encode_pretty
local json = require("jokymouse.json")
local str = json.encode_pretty({ name = "小丑鼠", level = 1 })
print(str)
decode
local json = require("jokymouse.json")
local data = json.decode('{"ok":true,"code":200,"items":["a","b"]}')
print(data.ok)
print(data.code)
print(data.items[1])
类型映射
| JSON 类型 | Lua 类型 |
|---|
null | nil |
true / false | boolean |
| number(整数) | integer |
| number(浮点) | number |
| string | string |
| array | table(key 从 1 开始的数组) |
| object | table(string key) |
与 http 模块配合使用
local json = require("jokymouse.json")
local http = require("jokymouse.http")
local res = http.post("https://api.example.com/order", {
headers = { ["Content-Type"] = "application/json" },
body = json.encode({ action = "buy", count = 1 })
})
if res.ok then
local data = json.decode(res.body)
print("订单 ID:" .. tostring(data.order_id))
end
错误处理
encode / decode 失败时会抛出运行时错误,可用 pcall 捕获:
local json = require("jokymouse.json")
local ok, result = pcall(json.decode, "not valid json")
if not ok then
print("解析失败:" .. tostring(result))
end