json. format Synchronous
Parse an existing JSON document and serialize it again with readable indentation. Use it to make pasted or downloaded JSON easier to inspect. Since this parses and re-encodes the document, it is not a formatting operation that preserves its original spelling.
Luau
json.format(
text: string,
options: JsonEncodeOptions?,
decodeOptions: JsonDecodeOptions?
) -> stringParameters
| Parameter | Type | Description |
|---|---|---|
text | string | JSON document to reformat. |
options | JsonEncodeOptions? | Optional pretty flag, indent width, indent string, or options table. See the encoding options below. |
decodeOptions | JsonDecodeOptions? | Optional boolean useNull flag or options table. Null preservation is enabled by default; maxDepth defaults to 256. |
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. |
Luau
JsonDecodeOptions = boolean | {useNull: boolean?, maxDepth: number?}| Field | Description |
|---|---|
useNull | Defaults to true, preserving JSON null as json.null. false converts null to nil, which can remove table entries. A boolean options argument is shorthand for this field. |
maxDepth | Maximum nesting depth. Defaults to 256; an integer is required and is clamped to 1–4096. |
Returns
stringPretty-printed JSON text. Invalid input raises a parse error.
Usage notes
The document is decoded and encoded again, so its original spacing is not preserved.
Example
Luau
local compact = '{"theme":"dark","colors":["pink","white"]}'
print(json.format(compact, { indent = " ", sortKeys = true }))