json.decodeSafe Synchronous

  • json.tryDecode

Parse JSON with an explicit success result so a script can handle malformed input without a parsing exception. Use it for user-supplied files or responses that may not contain valid JSON. Read the success flag first, since a valid JSON value can itself be false or null.

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 to parse.
optionsJsonDecodeOptions?Optional boolean useNull flag or options table. Null preservation is enabled by default; maxDepth defaults to 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 followed by the decoded value. On a parse failure: false, nil, an error message, and the error position.

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

Usage notes

Invalid argument types still raise an error; the safe result applies to parsing failures.

Example

Example
Luau
local ok, value, message, position = json.decodeSafe("{invalid}")
if ok then
    print(value)
else
    print(message, position)
end
Kawaii documentation