JSON

json.tryDecode

Attempts to parse a JSON string like json.decodeSafe and returns status values for parse errors.

Syntax

json.tryDecode(json: string, options?: DecodeOptions): boolean | any | nil | string | nil | number | nil

Arguments

NameTypeDescription
jsonstringJSON string to parse. The function reads this argument with string type checking.
options?DecodeOptionsOptional decode options. A boolean sets useNull. A table can set useNull and maxDepth.

Returns

NameTypeDescription
successbooleantrue when parsing succeeds, false when parsing fails inside the protected parse block.
decodedany | nilDecoded value on success. On parse failure, this return is nil.
errorMessagestring | nilError message on parse failure. The message is prefixed with json.decodeSafe and includes a near-position suffix.
errorPositionnumber | nilParser byte position from the parser on parse failure. This return is only present on failure.

Description

Attempts to parse a JSON string like json.decodeSafe and returns status values for parse errors.

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

It returns success (boolean), decoded (any | nil), errorMessage (string | nil), errorPosition (number | nil). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Decode JSON with status returns using the json.decodeSafe-compatible alias.

local ok, value, message, position = json.tryDecode('{"ready":true,"missing":null}', {
    useNull = true,
})

if ok then
    print(value.ready)
    print(json.isNull(value.missing))
else
    warn(message, position)
end

Types

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.