json.encode Synchronous

  • json.stringify

Serialize a Luau value as compact JSON. Use it before writing structured settings to a file or sending a JSON request body.

Syntax
Luau
json.encode(value: any, options: JsonEncodeOptions?) -> string

Parameters

Function parameters
ParameterTypeDescription
valueanyValue to serialize. Table shape and json.array/json.object markers decide between arrays and objects.
optionsJsonEncodeOptions?Optional pretty boolean, indentation width, indentation string, or options table. See Encoding options for all fields.

Argument fields

JsonEncodeOptions fields
Luau
JsonEncodeOptions = boolean | number | string | {
  pretty: boolean?, sortKeys: boolean?, emptyTableAsArray: boolean?,
  errorOnUnsupported: boolean?, encodeInvalidNumbersAsNull: boolean?,
  maxDepth: number?, indent: string?
}
FieldDescription
prettyAdd indentation and line breaks. encodePretty and format always enable this.
sortKeysSort object keys by their string representations before encoding. Defaults to false.
emptyTableAsArrayEncode an unmarked empty table as [] instead of {}. Explicit json.array/json.object metadata takes precedence.
errorOnUnsupportedRaise for unsupported values or object keys. By default, unsupported values become null and unsupported keys are skipped.
encodeInvalidNumbersAsNullDefaults to true. false makes NaN and infinite numbers raise an error.
maxDepthMaximum nesting depth. Defaults to 256; an integer is required and is clamped to 1–4096. Cyclic tables always raise.
indentIndentation 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

string

A JSON document string.

Usage notes

Unsupported values become null unless errorOnUnsupported is true. Invalid numbers become null by default. Cyclic tables raise an error.

For stable object-key order, set sortKeys in the options table.

Example

Example
Luau
local settings = { theme = "dark", scale = 1.25 }
local text = json.encode(settings, { sortKeys = true })
print(text)
Kawaii documentation