json.decodeSafe Synchronous

  • json.tryDecode

Parse JSON that may be malformed while keeping the error in return values. This is a good choice for a user-selected file or an external response.

Syntax
Luau
json.decodeSafe(
    text: string,
    options: JsonDecodeOptions?
) -> (true, value: JsonValue?) OR (false, nil, message: string, position: number)

Parameters

Function parameters
ParameterTypeDescription
textstringComplete JSON document.
optionsJsonDecodeOptions?Optional useNull boolean or options table. By default null becomes json.null and maxDepth is 256.

Argument fields

JsonDecodeOptions fields
Luau
JsonDecodeOptions = boolean | {useNull: boolean?, maxDepth: number?}
FieldDescription
useNullDefaults 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.
maxDepthMaximum nesting depth. Defaults to 256; an integer is required and is clamped to 1–4096.

Returns

(true, value: JsonValue?) OR (false, nil, message: string, position: number)

On success, true and the value. On a parse failure, false, nil, an error message, and a position.

JsonValue fields
Luau
JsonValue = string | number | boolean | JsonNull | {JsonValue} | {[string]: JsonValue}
JsonNull fields
Luau
JsonNull = typeof(json.null)

Usage notes

Bad argument types still raise an error. Read the success flag: a valid JSON document can itself decode to false or null.

Example

Example
Luau
local ok, value, message, position = json.decodeSafe('{broken}')
if ok then
    print(json.type(value))
else
    print("Invalid JSON at", position, message)
end
Kawaii documentation