Class yii\helpers\Json

Inheritanceyii\helpers\Json » yii\helpers\BaseJson
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/helpers/Json.php

Json is a helper class providing JSON data encoding and decoding.

It enhances the PHP built-in functions json_encode() and json_decode() by supporting encoding JavaScript expressions and throwing exceptions when decoding fails.

Public Properties

Hide inherited properties

Property Type Description Defined By
$jsonErrorMessages array List of JSON Error messages assigned to constant names for better handling of PHP <= 5.5. yii\helpers\BaseJson
$keepObjectType boolean Avoids objects with zero-indexed keys to be encoded as array Json::encode((object)['test']) will be encoded as an object not as an array. yii\helpers\BaseJson
$prettyPrint boolean|null Enables human readable output a.k.a. yii\helpers\BaseJson

Public Methods

Hide inherited methods

Method Description Defined By
decode() Decodes the given JSON string into a PHP data structure. yii\helpers\BaseJson
encode() Encodes the given value into a JSON string. yii\helpers\BaseJson
errorSummary() Generates a summary of the validation errors. yii\helpers\BaseJson
htmlEncode() Encodes the given value into a JSON string HTML-escaping entities so it is safe to be embedded in HTML code. yii\helpers\BaseJson

Protected Methods

Hide inherited methods

Method Description Defined By
handleJsonError() Handles encode() and decode() errors by throwing exceptions with the respective error message. yii\helpers\BaseJson
processData() Pre-processes the data before sending it to json_encode(). yii\helpers\BaseJson

Method Details

Hide inherited methods

decode() public static method

Defined in: yii\helpers\BaseJson::decode()

Decodes the given JSON string into a PHP data structure.

public static mixed decode ( $json, $asArray true )
$json string

The JSON string to be decoded

$asArray boolean

Whether to return objects in terms of associative arrays.

return mixed

The PHP data

throws yii\base\InvalidArgumentException

if there is any decoding error

                public static function decode($json, $asArray = true)
{
    if (is_array($json)) {
        throw new InvalidArgumentException('Invalid JSON data.');
    } elseif ($json === null || $json === '') {
        return null;
    }
    $decode = json_decode((string) $json, $asArray);
    static::handleJsonError(json_last_error());
    return $decode;
}

            
encode() public static method

Defined in: yii\helpers\BaseJson::encode()

Encodes the given value into a JSON string.

The method enhances json_encode() by supporting JavaScript expressions. In particular, the method will not encode a JavaScript expression that is represented in terms of a yii\web\JsExpression object.

Note that data encoded as JSON must be UTF-8 encoded according to the JSON specification. You must ensure strings passed to this method have proper encoding before passing them.

public static string encode ( $value, $options 320 )
$value mixed

The data to be encoded.

$options integer

The encoding options. For more details please refer to https://www.php.net/manual/en/function.json-encode.php. Default is JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE.

return string

The encoding result.

throws yii\base\InvalidArgumentException

if there is any encoding error.

                public static function encode($value, $options = 320)
{
    $expressions = [];
    $value = static::processData($value, $expressions, uniqid('', true));
    set_error_handler(function () {
        static::handleJsonError(JSON_ERROR_SYNTAX);
    }, E_WARNING);
    if (static::$prettyPrint === true) {
        $options |= JSON_PRETTY_PRINT;
    } elseif (static::$prettyPrint === false) {
        $options &= ~JSON_PRETTY_PRINT;
    }
    $json = json_encode($value, $options);
    restore_error_handler();
    static::handleJsonError(json_last_error());
    return $expressions === [] ? $json : strtr($json, $expressions);
}

            
errorSummary() public static method (available since version 2.0.14)

Defined in: yii\helpers\BaseJson::errorSummary()

Generates a summary of the validation errors.

public static string errorSummary ( $models, $options = [] )
$models yii\base\Model|yii\base\Model[]

The model(s) whose validation errors are to be displayed.

$options array

The tag options in terms of name-value pairs. The following options are specially handled:

  • showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise only the first error message for each attribute will be shown. Defaults to false.
return string

The generated error summary

                public static function errorSummary($models, $options = [])
{
    $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
    $lines = self::collectErrors($models, $showAllErrors);
    return static::encode($lines);
}

            
handleJsonError() protected static method (available since version 2.0.6)

Defined in: yii\helpers\BaseJson::handleJsonError()

Handles encode() and decode() errors by throwing exceptions with the respective error message.

protected static void handleJsonError ( $lastError )
$lastError integer

Error code from json_last_error().

throws yii\base\InvalidArgumentException

if there is any encoding/decoding error.

                protected static function handleJsonError($lastError)
{
    if ($lastError === JSON_ERROR_NONE) {
        return;
    }
    if (PHP_VERSION_ID >= 50500) {
        throw new InvalidArgumentException(json_last_error_msg(), $lastError);
    }
    foreach (static::$jsonErrorMessages as $const => $message) {
        if (defined($const) && constant($const) === $lastError) {
            throw new InvalidArgumentException($message, $lastError);
        }
    }
    throw new InvalidArgumentException('Unknown JSON encoding/decoding error.');
}

            
htmlEncode() public static method (available since version 2.0.4)

Defined in: yii\helpers\BaseJson::htmlEncode()

Encodes the given value into a JSON string HTML-escaping entities so it is safe to be embedded in HTML code.

The method enhances json_encode() by supporting JavaScript expressions. In particular, the method will not encode a JavaScript expression that is represented in terms of a yii\web\JsExpression object.

Note that data encoded as JSON must be UTF-8 encoded according to the JSON specification. You must ensure strings passed to this method have proper encoding before passing them.

public static string htmlEncode ( $value )
$value mixed

The data to be encoded

return string

The encoding result

throws yii\base\InvalidArgumentException

if there is any encoding error

                public static function htmlEncode($value)
{
    return static::encode($value, JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS);
}

            
processData() protected static method

Defined in: yii\helpers\BaseJson::processData()

Pre-processes the data before sending it to json_encode().

protected static mixed processData ( $data, &$expressions, $expPrefix )
$data mixed

The data to be processed

$expressions array

Collection of JavaScript expressions

$expPrefix string

A prefix internally used to handle JS expressions

return mixed

The processed data

                protected static function processData($data, &$expressions, $expPrefix)
{
    $revertToObject = false;
    if (is_object($data)) {
        if ($data instanceof JsExpression) {
            $token = "!{[$expPrefix=" . count($expressions) . ']}!';
            $expressions['"' . $token . '"'] = $data->expression;
            return $token;
        }
        if ($data instanceof \JsonSerializable) {
            return static::processData($data->jsonSerialize(), $expressions, $expPrefix);
        }
        if ($data instanceof \DateTimeInterface) {
            return static::processData((array)$data, $expressions, $expPrefix);
        }
        if ($data instanceof Arrayable) {
            $data = $data->toArray();
        } elseif ($data instanceof \SimpleXMLElement) {
            $data = (array) $data;
            // Avoid empty elements to be returned as array.
            // Not breaking BC because empty array was always cast to stdClass before.
            $revertToObject = true;
        } else {
            /*
             * $data type is changed to array here and its elements will be processed further
             * We must cast $data back to object later to keep intended dictionary type in JSON.
             * Revert is only done when keepObjectType flag is provided to avoid breaking BC
             */
            $revertToObject = static::$keepObjectType;
            $result = [];
            foreach ($data as $name => $value) {
                $result[$name] = $value;
            }
            $data = $result;
            // Avoid empty objects to be returned as array (would break BC without keepObjectType flag)
            if ($data === []) {
                $revertToObject = true;
            }
        }
    }
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            if (is_array($value) || is_object($value)) {
                $data[$key] = static::processData($value, $expressions, $expPrefix);
            }
        }
    }
    return $revertToObject ? (object) $data : $data;
}