Skip to content

Petrichor.Json#

Petrichor.Json is a JSON encoder/decoder bundled with Petrichor (rxi/json.lua 0.1.2). It is preloaded in the Luau VM, so require("Petrichor.Json") always works without a file in your mod folder.

Petrichor.Storage uses this module internally when saving store.json.

Loading#

local Json = require("Petrichor.Json")
import * as Json from "Petrichor.Json"

API#

Json.encode(value) -> string#

Encodes a Luau value as JSON.

Supported types: nil, booleans, numbers, strings, and tables. Use contiguous integer keys starting at 1 for arrays, string keys for objects.

local text = Json.encode({
    mod = "hello-cow",
    enabled = true,
    count = 3,
})
-- {"mod":"hello-cow","enabled":true,"count":3}
const text = Json.encode({
    mod: "hello-cow",
    enabled: true,
    count: 3,
})
// {"mod":"hello-cow","enabled":true,"count":3}

Json.decode(string) -> value#

Parses JSON into Luau values. Errors on invalid input.

local cfg = Json.decode('{"volume":0.8,"tags":["a","b"]}')
print(cfg.volume)  -- 0.8
const cfg = Json.decode('{"volume":0.8,"tags":["a","b"]}') as {
    volume: number
    tags: string[]
}
print(cfg.volume)  // 0.8

Example: mod config file#

Use Storage.asset() to read a bundled config file and Json.decode to parse it.

local Json    = require("Petrichor.Json")
local Storage = require("Petrichor.Storage")

local config = Json.decode(Storage.asset("config.json"))
import * as Json from "Petrichor.Json"
import * as Storage from "Petrichor.Storage"

const config = Json.decode(Storage.asset("config.json"))

For persistent player data, use Petrichor.Storage directly.


See also#