HOOZiDocs
Skip to content

json

JSON serialization / deserialization.

Type mapping (bidirectional):

LuaJSON
nilnull
boolbool
numbernumber (integers take the int path)
stringstring
Contiguous 1..N integer-indexed tablearray
Other tableobject
function / userdata(skipped + LOG_WARN)

json.encode(value, pretty?) → string

Parameters:

  • value : any — value to serialize
  • pretty? : bool = false — true uses 2-space indentation for readability

Returns "null" on serialization failure (rare, only when types are unrecoverable).


json.decode(text) → value | nil, err_msg

Parameters: text : string

Returns: on success, a single Lua value; on failure, (nil, error_string) — check with if v == nil then ....

A table received in Lua with contiguous 1..N integer keys = JSON array; other key shapes = JSON object. An empty table {} is encoded as "[]" by default (treated as an empty array); for an empty object, add any string key to force the non-array path.


Example

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 + error handling
local raw = file.read("conf/my_state.json") or ""
local loaded, err = json.decode(raw)
if not loaded then
    log.warn("Config parse failed: " .. err)
    loaded = { age = 0 }  -- fallback
end
print(loaded.name)

Pairs well with net.http for remote config pushes:

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("Reported")
        end
    end, 5)