Funzioni JSON

Nette\Utils\Json è una classe statica con funzioni di codifica e decodifica JSON. Gestisce le vulnerabilità delle diverse versioni di PHP e lancia eccezioni in caso di errore.

Installazione:

composer require nette/utils

Tutti gli esempi presuppongono che sia definito il seguente alias di classe:

use Nette\Utils\Json;

Uso

encode(mixed $value, bool $pretty=false, bool $asciiSafe=false, bool $htmlSafe=false, bool $forceObjects=false)string

Converte $value in formato JSON.

Quando $pretty è impostato, formatta JSON per facilitare la lettura e la chiarezza:

Json::encode($value); // restituisce JSON
Json::encode($value, pretty: true); // restituisce un JSON più chiaro

Quando $asciiSafe è impostato, genera un output ASCII, cioè sostituisce i caratteri unicode con le sequenze \uxxxx:

Json::encode('žluťoučký', asciiSafe: true);
// '"\u017elu\u0165ou\u010dk\u00fd"'

Il parametro $htmlSafe assicura che l'output non contenga caratteri con un significato speciale in HTML:

Json::encode('one<two & three', htmlSafe: true);
// '"one\u003Ctwo \u0026 three"'

Con $forceObjects, anche gli array con chiavi numeriche saranno 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"}'

Lancia un'eccezione Nette\Utils\JsonException in caso di errore.

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

decode(string $json, bool $forceArray=false)mixed

Analizza JSON in PHP.

L'impostazione $forceArray forza la restituzione di array invece che di oggetti:

Json::decode('{"variable": true}'); // restituisce un oggetto di tipo stdClass
Json::decode('{"variable": true}', forceArray: true); // restituisce un array

Lancia un'eccezione Nette\Utils\JsonException in caso di errore.

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

Come inviare un JSON da un presentatore?

È possibile utilizzare il metodo $this->sendJson($data), che può essere richiamato, ad esempio, nel metodo action*(), vedere Invio di una risposta.

versione: 4.0