You are browsing the unmaintained documentation for old Nette 2.3. See documentation for current Nette.

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;
use Nette\Utils\JsonException;

Usage

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

Converts $value to JSON format. The flag can be Json::PRETTY, which formats JSON for easier reading and clarity.

Json::encode($value); // returns JSON
Json::encode($value, Json::PRETTY); // returns readable JSON

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

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

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

Parses JSON to PHP value. The flag can be Json::FORCE_ARRAY, which forces an array instead of an object as the return value.

Json::decode('{"variable": TRUE}'); // returns an object of stdClass
Json::decode('{"variable": TRUE}', Json::FORCE_ARRAY); // returns an array
Json::decode('TRUE'); // return TRUE

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 Termination of presenter.

Improve this page