Version 2.4

Working with JSON – Nette\Utils\Json

Nette\Utils\Json is a static class with useful functions you can use to work with JSON. It sanitizes errors in different PHP versions and throws exceptions on errors.

The following examples use these aliases:

use Nette\Utils\Json;
use Nette\Utils\JsonException;

encode($value, $flags = 0)

Returns $value encoded into JSON. Accepts flag Json::PRETTY which formats JSON for better readability.

Json::encode($value); // Returns $value encoded in JSON
Json::encode($value, Json::PRETTY); // Returns formatted $value encoded in JSON

Method encode() throws JsonException on error.

try {
    $json = Json::encode($value);
} catch (JsonException $e) {
    // Exception handling

decode($json, $flags = 0)

Converts given JSON either in object or in array. Accepts flag Json::FORCE_ARRAY which forces an array instead of an object as the return value.

Json::decode('{"variable": true}'); // Returns an object of stdClass with attribute $variable
Json::decode('{"variable": true}', Json::FORCE_ARRAY); // Returns an array with key "variable" and value true

Method decode() throws JsonException on error.

try {
    $value = Json::decode($json);
} catch (JsonException $e) {
    // Exception handling