Skip to main content

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)

FieldType
Signature(value: any) → string
Returnsstring — JSON text
Common errorsraises on values serde_json can't represent (e.g. circular tables, function values)
Asyncno

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)

FieldType
Signature(text: string) → any
Returnsany — Lua value (table, string, number, boolean, or nil)
Common errorsraises on malformed JSON (json.decode('{not valid}') errors instead of returning nil)
Asyncno

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-triptrue/false encode and decode as JSON true/false.
  • nil keys are dropped — Lua's nil removes a key; encode skips it. Use a sentinel like 0 or "" if you need a "present-but-empty" slot.
  • No null value — there's no Lua representation of JSON null; decoded null becomes nil (which removes the key from the table).
  • Float vs integer — Lua 5.4 distinguishes 3 from 3.0; json.encode preserves the distinction (33, 3.03.0).