JSON

json.validate

Validates a JSON string by parsing one complete JSON value.

Syntax

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

Arguments

NameTypeDescription
jsonstringJSON string to validate. The function reads this argument with string type checking.
options?DecodeOptionsOptional decode options. A boolean sets useNull. A table can set useNull and maxDepth. maxDepth is clamped from 1 to 4096.

Returns

NameTypeDescription
validbooleantrue when parsing one complete JSON value succeeds. false when parsing fails inside the protected parse block.
errorMessagestring | nilError message on parse failure. The message is prefixed with json.validate and includes a near-position suffix. This return is only present on failure.
errorPositionnumber | nilParser byte position from the parser on parse failure. This return is only present on failure.

Description

Validates a JSON string by parsing one complete JSON value. On success it returns only true. On parse failure it returns false plus parser error details.

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 valid (boolean), errorMessage (string | nil), errorPosition (number | nil). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Check whether a string contains exactly one complete JSON value.

print(json.validate('{"value":42}'))

local valid, message, position = json.validate('{"value":42 trailing')

if not valid 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.