0 追蹤者

類別 yii\helpers\Json

繼承yii\helpers\Json » yii\helpers\BaseJson
版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/helpers/Json.php

Json 是一個提供 JSON 資料編碼和解碼功能的輔助類別。

它增強了 PHP 內建的 json_encode()json_decode() 函數,支援編碼 JavaScript 表達式,並在解碼失敗時拋出例外。

公有屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$jsonErrorMessages 陣列 JSON 錯誤訊息列表,已分配給常數名稱,以便更好地處理 PHP <= 5.5。 yii\helpers\BaseJson
$keepObjectType 布林值 避免將索引鍵為零的物件編碼為陣列。例如:Json::encode((object)['test']) 將會編碼為物件,而不是陣列。 yii\helpers\BaseJson
$prettyPrint 布林值|null 啟用人類可讀的輸出,又稱 yii\helpers\BaseJson

公有方法

隱藏繼承的方法

方法 描述 定義於
decode() 將給定的 JSON 字串解碼為 PHP 資料結構。 yii\helpers\BaseJson
encode() 將給定的值編碼為 JSON 字串。 yii\helpers\BaseJson
errorSummary() 產生驗證錯誤的摘要。 yii\helpers\BaseJson
htmlEncode() 將給定的值編碼為 JSON 字串,並對 HTML 實體進行跳脫,使其可以安全地嵌入在 HTML 程式碼中。 yii\helpers\BaseJson

受保護方法

隱藏繼承的方法

方法 描述 定義於
handleJsonError() 處理 encode()decode() 的錯誤,透過拋出包含各自錯誤訊息的例外。 yii\helpers\BaseJson
processData() 在將資料傳送至 json_encode() 之前,預先處理資料。 yii\helpers\BaseJson

方法詳細資訊

隱藏繼承的方法

decode() public static method

定義於: yii\helpers\BaseJson::decode()

將給定的 JSON 字串解碼為 PHP 資料結構。

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

要解碼的 JSON 字串

$asArray 布林值

是否以關聯陣列的形式傳回物件。

return mixed

PHP 資料

throws yii\base\InvalidArgumentException

如果發生任何解碼錯誤

                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

定義於: yii\helpers\BaseJson::encode()

將給定的值編碼為 JSON 字串。

此方法透過支援 JavaScript 表達式來增強 json_encode()。 特別是,此方法不會編碼以 yii\web\JsExpression 物件表示的 JavaScript 表達式。

請注意,根據 JSON 規範,編碼為 JSON 的資料必須是 UTF-8 編碼。 您必須確保傳遞給此方法的字串在傳遞之前具有正確的編碼。

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

要編碼的資料。

$options integer

編碼選項。 更多詳細資訊,請參閱 https://php.dev.org.tw/manual/en/function.json-encode.php。 預設值為 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE

return string

編碼結果。

throws yii\base\InvalidArgumentException

如果發生任何編碼錯誤。

                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)

定義於: yii\helpers\BaseJson::errorSummary()

產生驗證錯誤的摘要。

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

要顯示其驗證錯誤的模型。

$options 陣列

標籤選項,以名稱-值配對的形式呈現。 以下選項將被特別處理

  • showAllErrors:布林值,如果設定為 true,則會顯示每個屬性的所有錯誤訊息;否則,只會顯示每個屬性的第一個錯誤訊息。 預設值為 false
return string

產生的錯誤摘要

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

            
handleJsonError() 受保護的靜態方法 (自版本 2.0.6 起可用)

定義於: yii\helpers\BaseJson::handleJsonError()

處理 encode()decode() 的錯誤,透過拋出包含各自錯誤訊息的例外。

protected static void handleJsonError ( $lastError )
$lastError integer

來自 json_last_error() 的錯誤代碼。

throws yii\base\InvalidArgumentException

如果發生任何編碼/解碼錯誤。

                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() 公共靜態方法 (自版本 2.0.4 起可用)

定義於: yii\helpers\BaseJson::htmlEncode()

將給定的值編碼為 JSON 字串,並對 HTML 實體進行跳脫,使其可以安全地嵌入在 HTML 程式碼中。

此方法透過支援 JavaScript 表達式來增強 json_encode()。 特別是,此方法不會編碼以 yii\web\JsExpression 物件表示的 JavaScript 表達式。

請注意,根據 JSON 規範,編碼為 JSON 的資料必須是 UTF-8 編碼。 您必須確保傳遞給此方法的字串在傳遞之前具有正確的編碼。

public static string htmlEncode ( $value )
$value mixed

要編碼的資料

return string

編碼結果

throws yii\base\InvalidArgumentException

如果發生任何編碼錯誤

                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() 受保護的靜態方法

定義於: yii\helpers\BaseJson::processData()

在將資料傳送至 json_encode() 之前,預先處理資料。

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

要處理的資料

$expressions 陣列

JavaScript 表達式集合

$expPrefix string

內部用於處理 JS 表達式的前綴

return mixed

已處理的資料

                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 \Generator) {
            $_data = [];
            foreach ($data as $name => $value) {
                $_data[$name] = static::processData($value, $expressions, $expPrefix);
            }
            $data = $_data;
        } 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;
}