API / Minn / Json

Json final class

Minn\Json · public/minn/src/Minn/Json.php · 134 lines

JSON in and out, for the engine and for code written for Minn:

use Minn\Json;

Json::encode($rows); // {"url":"https://example.com/a","name":"Café"} Json::decode($text); // objects as arrays; JsonException when it is not JSON Json::decode($stored, or: []); // the fallback, for text that may be empty or broken Json::file($path); // the same, read from a file; the error names the file

encode() writes slashes and characters as themselves unless flags say otherwise (Json::ESCAPED is the form WordPress writes, which REST bodies keep). A string cut mid-character still encodes: each invalid byte becomes "?", as wp_json_encode() does it (probe functions-utils). What cannot be encoded even then (NAN, nesting past the depth) throws a JsonException.

Constants and properties

constREADABLE = 320

Slashes and non-ASCII characters written as themselves: encode()'s default.

constESCAPED = 0

Slashes and non-ASCII characters escaped, as wp_json_encode() and the REST API write them.

Public

staticencode(mixed $value, int $flags = self::READABLE, int $depth = 512): string#

A value as JSON; invalid UTF-8 is repaired, never a reason to fail.

$flagsintjson_encode() flags; JSON_THROW_ON_ERROR here skips the repair, as it does for wp_json_encode()
staticdecode(string $text, mixed $or = NULL): mixed#

The value the text holds, objects as arrays; with `or:` given, that comes back instead of an exception.

staticfile(string $path, mixed $or = NULL): mixed#

The value a JSON file holds, objects as arrays; with `or:` given, a missing or broken file gives that instead.

staticrepair(mixed $value, int $depth = 512): mixed#

A value with every string and key made valid UTF-8, each invalid byte becoming "?", objects read as plain objects of their public properties.

staticdecodeKeepingEmptyObjects(string $json): mixed#

JSON as arrays, but an empty object stays an object: an in-process REST answer keeps `{}` where the reference's data holds an empty object (a global style's emptied settings), which decoding to arrays would turn into `[]`.

Internals 2

Private and protected methods: how the class does its work. Not a contract; they change whenever the code is tidied.

privatemember(mixed $item, int $depth): mixed#

One member of an array or object: a nested one goes a level deeper, a string is repaired.

privatetext(string $text): string#

A string made valid UTF-8: each invalid byte becomes "?", the valid characters stay.