Skip to content

Core\Json::decode

Core\Json::decode(string $json, {maxDepth?: uint}): mixedCore\Json::decode(
    string $json,
    {maxDepth?: uint},
): mixed

Reads a JSON text and returns the value it contains.

A JSON object becomes an array with string keys, and a JSON array becomes a list. Numbers, strings, true, false and null stay what they are. The result has the type mixed, so you convert each part with as before you use it, for example $person["name"] as string.

If the text is not valid JSON, decode throws a ParseError. It also throws one when the document is nested deeper than the maxDepth option allows, which is 512 levels by default, or when a whole number is too large or too small for int. It never returns null to report an error.

Good to know: when you know the structure of the document in advance, Core\Json::decodeAs reads it straight into a class or a shape.

The examples below read the fields of one object, show three texts that throw a ParseError, and add up the total of a shopping cart.

Parameters

  • $jsonstringThe JSON text to parse.

Options

  • maxDepthuintoptionalThe deepest nesting allowed. A scalar document is depth 1, and [1] is depth 2. The default is 512, and the largest value is 1024.

Return value

Returns mixed. The decoded value: null, bool, int, float, string, or an array. A JSON object is always a string-keyed array, never an object.

Errors

  • ParseError$json is not a valid JSON document, nests deeper than maxDepth, has an object with the same key twice, or contains a whole number too large for int. The error has one issue, and its path is empty.
  • LogicErrormaxDepth is 0 or above 1024.

Examples

Reading the fields of an object

<?nvs
// Shows how to read the fields of a JSON object.
string $text = "{\"name\":\"Ada\",\"age\":36,\"languages\":[\"English\",\"French\"]}";
// `Core\Json::decode` returns a `mixed` value.
// A JSON object becomes an array with string keys.
var $person = Core\Json::decode($text) as array<mixed>;
// `as` converts each field to the type you need.
tainted string $name = $person['name'] as string;
int $age = $person['age'] as int;
var $languages = $person['languages'] as array<mixed>;
// This prints `Ada is 36 and speaks 2 languages`.
echo $name, ' is ', $age, ' and speaks ', Core\Arr::count($languages), " languages\n";
Output
Ada is 36 and speaks 2 languages

Text that is not valid json

<?nvs
// Shows the errors `Core\Json::decode` throws for text it cannot read.
// A key without quotes, four levels of nesting, and a number one more than the largest `int`.
array<string> $texts = [
"{name: \"Ada\"}",
'[[[1]]]',
'9223372036854775808',
];
// The option `maxDepth: 3` allows at most three levels.
// Each call throws a `ParseError`, so this prints three error messages.
foreach ($texts as string $text) {
try {
Core\Json::decode($text, { maxDepth: 3 });
echo "decoded\n";
} catch (ParseError $error) {
echo $error->message, "\n";
}
}
Output
Core\Json::decode(): key must be a string at line 1 column 2
Core\Json::decode(): nesting is deeper than the `maxDepth` of 3 at line 1 column 3
Core\Json::decode(): the integer 9223372036854775808 is too large for `int` at line 1 column 19

Adding up a shopping cart

<?nvs
// Shows a program that reads a shopping cart sent as JSON and adds up its total.
// A browser sends this text in the body of a request.
string $body = "{\"items\":[{\"name\":\"Tea\",\"cents\":450,\"count\":2},"
. "{\"name\":\"Cup\",\"cents\":1200,\"count\":1}]}";
var $cart = Core\Json::decode($body) as array<mixed>;
var $items = $cart['items'] as array<mixed>;
// Each item is also an array with string keys, so it is converted with `as` too.
int $total = 0;
foreach ($items as mixed $entry) {
var $item = $entry as array<mixed>;
$total = $total + ($item['cents'] as int) * ($item['count'] as int);
}
// This prints `2 items, 2100 cents`.
echo Core\Arr::count($items), ' items, ', $total, " cents\n";
Output
2 items, 2100 cents