JSON

json.decodeSafe

Parses JSON with the same parsing behavior as json.decode and returns a success flag instead of throwing for parse errors.

Syntax

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

Arguments

NameTypeDescription
jsonstringJSON text to parse. This argument is checked as a string before parse errors are caught.
options?DecodeOptionsOptional decode options. A boolean sets useNull directly. A table can set useNull and maxDepth; maxDepth is clamped from 1 to 4096. Invalid option argument types are checked before parse errors are caught.

Returns

NameTypeDescription
successbooleanTrue when parsing succeeds, false when the parser reports an error.
decodedany | nilDecoded value on success, nil on parse failure. Valid JSON false returns success as true and decoded as false, so check the success return value.
errorMessagestring | nilError message on parse failure, otherwise nil. The message includes the json.decodeSafe prefix and parser position.
errorPositionnumber | nilParser byte position on parse failure, otherwise nil.

Description

Parses JSON with the same parsing behavior as json.decode and returns a success flag instead of throwing 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

Parse JSON and use the success return value to separate valid false or nil results from parse failures.

local ok, value = json.decodeSafe("false")

if ok then
    print(value == false)
end

local parsed, _, message, position = json.decodeSafe("{")
if not parsed then
    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.