Lavorare con JSON
Nette\Utils\Json è una classe statica con funzioni per la codifica e la decodifica del formato JSON. Gestisce le vulnerabilità delle diverse versioni di PHP e lancia eccezioni in caso di errori.
Installazione:
composer require nette/utils
Tutti gli esempi presuppongono la creazione di un alias:
use Nette\Utils\Json;
Utilizzo
encode (mixed $value, bool $pretty=false, bool $asciiSafe=false, bool $htmlSafe=false, bool $forceObjects=false): string
Converte $value
nel formato JSON.
Impostando $pretty
su true, formatta il JSON per una lettura e una chiarezza più semplici:
Json::encode($value); // restituisce JSON
Json::encode($value, pretty: true); // restituisce un JSON più leggibile
Con $asciiSafe
genera un output in ASCII, ovvero i caratteri unicode vengono sostituiti con sequenze
\uxxxx
:
Json::encode('žluťoučký', asciiSafe: true);
// '"\u017elu\u0165ou\u010dk\u00fd"'
Il parametro $htmlSafe
garantisce che l'output non contenga caratteri che hanno un significato speciale
in HTML:
Json::encode('one<two & three', htmlSafe: true);
// '"one\u003Ctwo \u0026 three"'
Con $forceObjects
, anche gli array con chiavi numeriche verranno codificati come oggetti JavaScript:
Json::encode(['a', 'b', 'c']);
// '["a","b","c"]'
Json::encode(['a', 'b', 'c'], forceObjects: true);
// '{"0":"a","1":"b","2":"c"}'
In caso di errore, lancia un'eccezione Nette\Utils\JsonException
.
try {
$json = Json::encode($value);
} catch (Nette\Utils\JsonException $e) {
// Gestione dell'eccezione
}
decode (string $json, bool $forceArray=false): mixed
Analizza JSON in PHP.
L'impostazione $forceArray
forza la restituzione di array invece di oggetti:
Json::decode('{"variable": true}'); // restituisce un oggetto di tipo stdClass
Json::decode('{"variable": true}', forceArrays: true); // restituisce un array
In caso di errore, lancia un'eccezione Nette\Utils\JsonException
.
try {
$value = Json::decode($json);
} catch (Nette\Utils\JsonException $e) {
// Gestione dell'eccezione
}
Come inviare JSON da un presenter?
A tale scopo è possibile utilizzare il metodo $this->sendJson($data)
, che possiamo chiamare ad esempio nel
metodo action*()
, vedi Invio della
risposta.