json. encode Synchronous
json.stringify
Serialize a Luau value into JSON text, with options for formatting, key order, unsupported values, and nesting depth. Use it before saving a table with writefile or sending a JSON request body. The options let you choose compact storage or stable, readable output.
Luau
json.encode(value: any, options: JsonEncodeOptions?) -> stringParameters
| Parameter | Type | Description |
|---|---|---|
value | any | Value to serialize. Tables become JSON arrays or objects according to their shape and metadata. |
options | JsonEncodeOptions? | Optional pretty flag, indent width, indent string, or options table. See the encoding options below. |
Argument fields
Luau
JsonEncodeOptions = boolean | number | string | {
pretty: boolean?, sortKeys: boolean?, emptyTableAsArray: boolean?,
errorOnUnsupported: boolean?, encodeInvalidNumbersAsNull: boolean?,
maxDepth: number?, indent: string?
}| Field | Description |
|---|---|
pretty | Add indentation and line breaks. encodePretty and format always enable this. |
sortKeys | Sort object keys by their string representations before encoding. Defaults to false. |
emptyTableAsArray | Encode an unmarked empty table as [] instead of {}. Explicit json.array/json.object metadata takes precedence. |
errorOnUnsupported | Raise for unsupported values or object keys. By default, unsupported values become null and unsupported keys are skipped. |
encodeInvalidNumbersAsNull | Defaults to true. false makes NaN and infinite numbers raise an error. |
maxDepth | Maximum nesting depth. Defaults to 256; an integer is required and is clamped to 1–4096. Cyclic tables always raise. |
indent | Indentation string, truncated to 32 characters. Defaults to two spaces. A numeric options argument selects an indentation width clamped to 0–16 spaces and enables pretty output. |
Returns
stringThe serialized JSON string.
Usage notes
Unsupported values become JSON null unless errorOnUnsupported is true. Invalid numbers become null by default.
Example
Luau
local text = json.encode({ theme = "dark", scale = 1.25 }, { sortKeys = true })
print(text)