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:
All examples assume the following class alias is defined:
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:
When $asciiSafe
is set, it generates ASCII output, i.e. it replaces the unicode characters with
\uxxxx
sequences:
The $htmlSafe
parameter ensures that the output does not contain characters with special meaning in HTML:
With $forceObjects
, even arrays with numeric keys will be encoded as JavaScript objects:
It throws an Nette\Utils\JsonException
exception on error.
decode(string $json, bool $forceArray=false): mixed
Parses JSON to PHP.
Setting $forceArray
forces the return of arrays instead of objects:
It throws an Nette\Utils\JsonException
exception on error.
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.