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.
| PHP | Rust |
|---|---|
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_* constants | Flags |
JsonException / ValueError | Error (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 forjson_encode,json_decodeandjson_validate.
Enums§
Constants§
- DEFAULT_
DEPTH PHP_JSON_PARSER_DEFAULT_DEPTH: the default$depthof every function.
Functions§
- decode
json_decode($json, $assoc, $depth, $flags).- decode_
ext decodeinto aValueof any extensionX(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 ofsand 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
sasjson_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 returnstrue.