小丑鼠

JokyMouse 开发者文档

小丑鼠 Latest

jokymouse.json API

jokymouse.json 模块通过 require("jokymouse.json") 加载,提供 Lua 与 JSON 之间的序列化与反序列化能力。

local json = require("jokymouse.json")

可用函数

函数签名说明
encodejson.encode(value)Lua 值 → JSON 字符串(紧凑格式)
encode_prettyjson.encode_pretty(value)Lua 值 → JSON 字符串(缩进格式)
decodejson.decode(str)JSON 字符串 → Lua 值

encode

local json = require("jokymouse.json")

local str = json.encode({ action = "buy", count = 3, tags = { "hot", "new" } })
-- 输出: {"action":"buy","count":3,"tags":["hot","new"]}
print(str)

类型映射

Lua 类型JSON 类型
nilnull
booleantrue / false
integernumber(整数)
numbernumber(浮点);NaN / Infinity 会抛出错误
stringstring
table(数组)array(key 为连续正整数 1..n
table(对象)object(其他情况)
其他类型抛出错误

encode_pretty

local json = require("jokymouse.json")

local str = json.encode_pretty({ name = "小丑鼠", level = 1 })
print(str)
-- {
--   "level": 1,
--   "name": "小丑鼠"
-- }

decode

local json = require("jokymouse.json")

local data = json.decode('{"ok":true,"code":200,"items":["a","b"]}')
print(data.ok)        -- true
print(data.code)      -- 200
print(data.items[1])  -- a

类型映射

JSON 类型Lua 类型
nullnil
true / falseboolean
number(整数)integer
number(浮点)number
stringstring
arraytable(key 从 1 开始的数组)
objecttable(string key)

与 http 模块配合使用

local json = require("jokymouse.json")
local http = require("jokymouse.http")

-- 发送 JSON 请求体
local res = http.post("https://api.example.com/order", {
  headers = { ["Content-Type"] = "application/json" },
  body = json.encode({ action = "buy", count = 1 })
})

-- 解析 JSON 响应
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