Files
yii2/docs/guide/helper-json.md
rhertogh db39f7c955 Json pretty print (#18726)
* Added pretty print support to Json helper

* Updated documentation for `yii\helpers\Json::$prettyPrint`

* Fixed line ending in \yiiunit\framework\helpers\JsonTest::testPrettyPrint for windows

* Added helper-json.md link in docs/guide/README.md

* Capitalized JSON in descriptions

Co-authored-by: Alexander Makarov <sam@rmcreative.ru>

Co-authored-by: Alexander Makarov <sam@rmcreative.ru>
Co-authored-by: Bizley <pawel@positive.codes>
2021-06-27 14:08:41 +02:00

1.3 KiB

Json Helper

Json helper provides a set of static methods for encoding and decoding JSON. It handles encoding errors and the [[yii\helpers\Json::encode()]] method will not encode a JavaScript expression that is represented in terms of a [[yii\web\JsExpression]] object. By default, ecoding is done with the JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE options. Please see PHP:json_encode for more information.

Pretty Print

By default the [[yii\helpers\Json::encode()]] method will output unformatted JSON (e.g. without whitespaces). To make it more readable for humans you can turn on "pretty printing".

Note: Pretty Print can useful for debugging during development but is not recommended in a production environment.

To enable pretty print in a single instance you can specify it as an option. E.g.

$data = ['a' => 1, 'b' => 2];
$json = yii\helpers\Json::encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

You can also enable pretty printing of the JSON helper globally. For example in your config for or index.php:

yii\helpers\Json::$prettyPrint = YII_DEBUG; // use "pretty" output in debug mode