JSON
Lua-side JSON encode/decode. Powered by serde_json underneath. The pair lives on the json global as plain functions (not method calls — no self arg).
Methods
json.encode(value)
| Field | Type |
|---|---|
| Signature | (value: any) → string |
| Returns | string — JSON text |
| Common errors | raises on values serde_json can't represent (e.g. circular tables, function values) |
| Async | no |
Sequential numeric keys ({1, 2, 3}) serialize as JSON arrays; mixed/string keys serialize as objects.
local s = json.encode({ a = 1, b = "hi", c = { 1, 2, 3 } })
-- s = '{"a":1,"b":"hi","c":[1,2,3]}'
json.decode(text)
| Field | Type |
|---|---|
| Signature | (text: string) → any |
| Returns | any — Lua value (table, string, number, boolean, or nil) |
| Common errors | raises on malformed JSON (json.decode('{not valid}') errors instead of returning nil) |
| Async | no |
JSON arrays come back as 1-indexed Lua tables (t[1], not t[0] or t["1"]).
local t = json.decode('{"a":1,"b":"hi","c":[1,2,3]}')
print(t.a, t.b, t.c[1], t.c[2], t.c[3]) -- 1 hi 1 2 3
Round-trip
--!strict
local payload = { name = "asdsa", count = 7, online = true }
local raw = json.encode(payload)
local back = json.decode(raw)
assert(back.name == "asdsa")
assert(back.count == 7)
assert(back.online == true)
Pair with http
You don't need to encode manually when posting JSON — pass the Lua table to http.post(..., { json = ... }) and it gets serialized for you:
local res = http.post("https://api.example.com/data", {
json = { name = "seraph", count = 42 },
headers = { ["X-Auth"] = "token" },
})
local body = json.decode(res.body)
See HTTP for the full request/response shape.
Quirks
- Booleans round-trip —
true/falseencode and decode as JSONtrue/false. nilkeys are dropped — Lua'snilremoves a key; encode skips it. Use a sentinel like0or""if you need a "present-but-empty" slot.- No
nullvalue — there's no Lua representation of JSONnull; decodednullbecomesnil(which removes the key from the table). - Float vs integer — Lua 5.4 distinguishes
3from3.0;json.encodepreserves the distinction (3→3,3.0→3.0).