JSON Functions

Nette\Utils\Json is a static class with JSON encoding and decoding functions. It handles vulnerabilities in different PHP versions and throws exceptions on errors.

Installation:

composer require nette/utils

All examples assume the following class alias is defined:

use Nette\Utils\Json;

Usage

encode (mixed $value, bool $pretty=false, bool $asciiSafe=false, bool $htmlSafe=false, bool $forceObjects=false)string

Converts $value to JSON format.

When $pretty is set, it formats JSON for easier reading and clarity:

Json::encode($value); // returns JSON
Json::encode($value, pretty: true); // returns clearer JSON

When $asciiSafe is set, it generates ASCII output, i.e. it replaces the unicode characters with \uxxxx sequences:

Json::encode('žluťoučký', asciiSafe: true);
// '"\u017elu\u0165ou\u010dk\u00fd"'

The $htmlSafe parameter ensures that the output does not contain characters with special meaning in HTML:

Json::encode('one<two & three', htmlSafe: true);
// '"one\u003Ctwo \u0026 three"'

With $forceObjects, even arrays with numeric keys will be encoded as JavaScript objects:

Json::encode(['a', 'b', 'c']);
// '["a","b","c"]'
Json::encode(['a', 'b', 'c'], forceObjects: true);
// '{"0":"a","1":"b","2":"c"}'

It throws an Nette\Utils\JsonException exception on error.

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

decode (string $json, bool $forceArray=false)mixed

Parses JSON to PHP.

Setting $forceArray forces the return of arrays instead of objects:

Json::decode('{"variable": true}'); // returns an object of type stdClass
Json::decode('{"variable": true}', forceArrays: true); // returns an array

It throws an Nette\Utils\JsonException exception on error.

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

How to Send a JSON from a Presenter?

You can use the $this->sendJson($data) method, which can be called, for example, in the action*() method, see Sending a Response.

version: 4.0 3.x 2.x