Skip to content

json

JSON codec. Output is pretty-printed with 2-space indent and a trailing newline. See the formats overview for the shared codec shape and encoding rules common to every format.

Examples

Materialize a settings file:

lua
local rb = require("rootbeer")

rb.json.write("~/.config/myapp/settings.json", {
  theme = "dark",
  recent = { "a.txt", "b.txt" },
})

Patch a single field in place:

lua
local cfg = rb.json.read("~/.config/myapp/settings.json")
cfg.theme = "light"
rb.json.write("~/.config/myapp/settings.json", cfg)

Encode without touching disk:

lua
local payload = rb.json.encode({ ok = true, data = { 1, 2, 3 } })

Notes

  • NaN and Infinity are rejected — JSON cannot represent them. Filter these out of your tables before encoding.

API

rootbeer.json.decode(s)

Parses a JSON string into a Lua table.

Parameters

sstring
The JSON-encoded string.

Returns

table — The decoded value.

rootbeer.json.encode(t)

Serializes a Lua table to a JSON string with 2-space indentation.

Parameters

ttable
The table to serialize.

Returns

string — The JSON-encoded string (no trailing newline).

rootbeer.json.read(path)

Reads and decodes a JSON file. Equivalent to decode(slurp(path)). Path supports ~ expansion and is resolved against the script directory. This call is synchronous — the file must exist at plan time.

Parameters

pathstring
The file to read.

Returns

table — The decoded value.

rootbeer.json.write(path, t)

Encodes a table and writes it to a file. Equivalent to rb.file(path, encode(t)). The write is deferred until the apply stage. A trailing newline is always added so the file is well-formed.

Parameters

pathstring
The destination file path.
ttable
The table to serialize.