--!strict -- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. -- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers -- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so -- they write back as {}; opts.ordered makes every object a Types.object with its key order. -- -- local Json = require("@formats/codecs/Json") -- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input -- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err -- for ev, x in Json.events(text) do ... end -- pull events without building the tree -- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values -- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring() -- -- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer; -- writer() builds output incrementally and flush() hands back the text so far. Never throws. local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Decode = require("@formats/codecs/Json/Decode") local Encode = require("@formats/codecs/Json/Encode") local Json = {} export type DecodeOptions = Decode.Options export type EncodeOptions = Encode.Options Json.null = Types.null Json.object = Types.object Json.keys = Types.keys Json.set = Types.set local function text(src: any): (string?, Err.Err?) if type(src) == "string" then return src, nil elseif type(src) == "buffer" then return buffer.tostring(src), nil end return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) end local function fail(msg: any, at: any, n: number): Err.Err local m = tostring(msg) local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n then Err.TRUNCATED elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT else Err.CORRUPT return Err.new(code, m, at) end -- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is -- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil. function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?) local s, terr = text(src) if not s then return nil, terr end local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1 local v, ni, at = Decode.value(s, i, opts) if v == nil then return nil, fail(ni, at, #s) end local e = string.match(s, "^[ \t\n\r]*()", ni) :: any if e <= #s then return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1) end return v, nil end -- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading -- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left. function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any) local s, terr = text(src) if not s then return nil, terr end local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any if i > #s then return nil, nil end local v, ni, at = Decode.value(s, i, opts) if v == nil then return nil, fail(ni, at, #s) end return v, ni end -- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A -- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?) local s, terr = text(src) local pos = 1 local index = 0 local dead = false return function(): (number?, any, Err.Err?) if dead then return nil end index += 1 if not s then dead = true return index, nil, terr end local v, ni = Json.decodeAt(s, pos, opts) if v == nil then dead = true if ni == nil then return nil end return index, nil, ni end pos = ni return index, v, nil end end -- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key), -- "value" (a scalar), and on bad input one final "error", Err. function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any) local s, terr = text(src) if not s then local done = false return function(): (string?, any) if done then return nil, nil end done = true return "error", terr end end local str: string = s local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1 local nextEv = Decode.events(str, i, opts) return function(): (string?, any) local ev, v, at = nextEv() if ev == "error" then return ev, fail(v, at, #str) end return ev, v end end -- encode(value, opts?) -> string | nil, Err function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) local s, msg = Encode.encode(value, opts) if not s then return nil, Err.new(Err.ARG, msg or "cannot encode") end return s, nil end Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf) -- ------------------------------------------------------------------------------------------------ writer -- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any -- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key -- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing. export type Writer = { err: Err.Err?, beginObject: (self: Writer) -> Writer, endObject: (self: Writer) -> Writer, beginArray: (self: Writer) -> Writer, endArray: (self: Writer) -> Writer, key: (self: Writer, k: string) -> Writer, value: (self: Writer, v: any) -> Writer, flush: (self: Writer) -> string, tostring: (self: Writer) -> (string?, Err.Err?), } function Json.writer(opts: EncodeOptions?): Writer local st = Encode.state(opts) local ind = st.indent local kinds: { boolean } = {} -- true = object local counts: { number } = {} local depth = 0 local keyDone = false -- an object's key written, its value due local flushed: { string } = {} local w: any = { err = nil } local function bad(msg: string) if not w.err then w.err = Err.new(Err.ARG, msg) end end -- before an element: a comma / newline as needed; false when the position is wrong local function slot(isKey: boolean): boolean if w.err then return false end if depth == 0 then if counts[0] and counts[0] > 0 then bad("one top-level value only") return false end counts[0] = 1 return true end local obj = kinds[depth] if obj and not isKey then if not keyDone then bad("an object member needs a key first") return false end keyDone = false return true end if isKey and not obj then bad("key outside an object") return false end if isKey and keyDone then bad("two keys in a row") return false end if counts[depth] > 0 then table.insert(st.out, ",") end counts[depth] += 1 if ind then table.insert(st.out, "\n" .. string.rep(ind, depth)) end return true end local function open(obj: boolean) if slot(false) then table.insert(st.out, if obj then "{" else "[") depth += 1 kinds[depth], counts[depth] = obj, 0 end return w end local function close(obj: boolean) if w.err then return w end if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then bad(if obj then "unbalanced endObject" else "unbalanced endArray") return w end if ind and counts[depth] > 0 then table.insert(st.out, "\n" .. string.rep(ind, depth - 1)) end table.insert(st.out, if obj then "}" else "]") depth -= 1 return w end function w.beginObject(_self: Writer): Writer return open(true) end function w.beginArray(_self: Writer): Writer return open(false) end function w.endObject(_self: Writer): Writer return close(true) end function w.endArray(_self: Writer): Writer return close(false) end function w.key(_self: Writer, k: string): Writer if type(k) ~= "string" then bad("key must be a string") elseif slot(true) then table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":")) keyDone = true end return w end function w.value(_self: Writer, v: any): Writer if slot(false) then st.n = #st.out if not Encode.write(st, v, depth) then bad(st.err or "cannot encode") end end return w end function w.flush(_self: Writer): string local s = table.concat(st.out) table.clear(st.out) st.n = 0 table.insert(flushed, s) return s end function w.tostring(_self: Writer): (string?, Err.Err?) if w.err then return nil, w.err end if depth ~= 0 then return nil, Err.new(Err.ARG, "unclosed object / array") end return table.concat(flushed) .. table.concat(st.out), nil end return w :: Writer end return Json