JSON Functions

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.


encode(mixed $value, int $flags=0): string

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

use Nette\Utils\Json;

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

Method encode() throws Nette\Utils\JsonException on error.

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

decode(string $json, int $flags=0): mixed

Converts a given JSON either to an object or to an 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 Nette\Utils\JsonException on error.

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

MVC – Presenter

How to send a JSON from a presenter? We can use prepared method $this->sendJson($data), may be called at action**().

By calling sendJson() the presenter gets immediately terminated. More info can be found in the presenter's lifecycle.