JSON

json.format

Parses a JSON string and re-encodes it as readable formatted JSON using Real's JSON parser and encoder.

Syntax

json.format(json: string, encodeOptions?: EncodeOptions, decodeOptions?: DecodeOptions): string

Arguments

NameTypeDescription
jsonstringJSON string to parse before formatting. The function reads this argument with string type checking.
encodeOptions?EncodeOptionsOptional encode options passed to the re-encode step. json.format reads the same encode options as json.encode, then forces pretty to true.
decodeOptions?DecodeOptionsOptional decode options used while parsing the input JSON. A boolean sets useNull. A table can set useNull and maxDepth.

Returns

NameTypeDescription
formattedstringReadable formatted JSON string produced after parsing and re-encoding the input.

Description

Parses a JSON string and re-encodes it as readable formatted JSON using Real's JSON parser and encoder.

Call it with 3 parameter(s): json, encodeOptions, decodeOptions. The argument table explains which values are required and which ones only refine the behavior.

It returns formatted (string). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Parse existing JSON and re-encode it as readable formatted JSON.

local compact = '{"b":2,"a":1}'
local formatted = json.format(compact, {
    pretty = true,
    sortKeys = true,
}, {
    useNull = true,
})

print(formatted)

Types

EncodeOptions

Controls JSON serialization and formatting.

pretty? boolean Enables formatted, multi-line JSON output.sortKeys? boolean Sorts object keys before encoding.emptyTableAsArray? boolean Encodes an empty table as an array instead of an object.errorOnUnsupported? boolean Raises an error instead of substituting unsupported values.encodeInvalidNumbersAsNull? boolean Encodes NaN and infinite numbers as JSON null.maxDepth? integer Sets the maximum nesting depth, clamped from 1 to 4096.indent? string Sets the indentation string, limited to 32 characters.

DecodeOptions

Controls JSON parsing behavior.

useNull? boolean Represents JSON null with the library's null sentinel instead of nil.maxDepth? integer Sets the maximum nesting depth, clamped from 1 to 4096.