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, 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 Sending a Response.

version: 4.0 3.x 2.x