Skip to main content

Module json

Module json 

Source
Expand description

json_encode, json_decode, json_validate, json_last_error and json_last_error_msg, as PHP 8.5’s ext/json implements them.

PHPRust
json_encode($v, $flags, $depth)encode (Value)
json_decode($s, $assoc, $depth, $flags)decode (Value), decode_value (serde_json::Value, $assoc = true)
json_validate($s, $depth, $flags)validate
json_last_error(), json_last_error_msg()ErrorCode::code, ErrorCode::message of the returned error
JSON_* constantsFlags
JsonException / ValueErrorError (Error::php_class)

There is no global “last error”: each call returns its error. PHP’s json_last_error() after a call without JSON_THROW_ON_ERROR is the code of the returned error (0 on success).

Faithful details: floats print with serialize_precision = -1 (crate::number::serialize); strings are validated as UTF-8 exactly like PHP (php_next_utf8_char when encoding, the scanner’s byte ranges when decoding, so JSON_INVALID_UTF8_SUBSTITUTE replaces the same byte runs); errors follow PHP’s precedence (the first error in input order when decoding, the last one recorded when encoding); the decoder reports the same error as PHP’s bison parser when nesting exhausts its 10000-entry stack, and never recurses.

Objects other than stdClass are Value::Ext: they encode as an object of their Extension::to_array (what json_encode does for an ArrayObject, such as Utopia\Database\Document). Not modelled: JsonSerializable, enums, recursion (a Value cannot contain itself) and the engine’s stack-size limit when encoding values nested thousands of levels deep.

Structs§

Flags
JSON_* option bits for json_encode, json_decode and json_validate.

Enums§

Error
Why a JSON function failed.
ErrorCode
JSON_ERROR_*: what json_last_error() returns.

Constants§

DEFAULT_DEPTH
PHP_JSON_PARSER_DEFAULT_DEPTH: the default $depth of every function.

Functions§

decode
json_decode($json, $assoc, $depth, $flags).
decode_ext
decode into a Value of any extension X (a decoded value never holds one), so a library with its own object type decodes without a copy.
decode_value
json_decode($json, true, $depth, $flags) into the request model (serde_json::Value): PHP arrays that are lists become JSON arrays (so {"0":"a"} decodes to ["a"], as PHP’s [0 => 'a'] is a list), other arrays objects; empty objects become [].
encode
json_encode($value, $flags, $depth).
next_utf8_char
php_next_utf8_char: the code point at the start of s and its length, or the number of bytes PHP skips as one invalid sequence (UTR #36 strategy 2: an invalid sequence never swallows a byte that could start a valid one).
push_int
Appends the decimal digits of i (no allocation).
push_string
Appends s as json_encode() writes a string without options, and says whether it could: PHP refuses one that is not UTF-8, and what is appended then is not JSON.
validate
json_validate($json, $depth, $flags): Ok(()) when PHP returns true.