Why use CJSON encode when we have json_encode

2019-02-11 10:40发布

I am building an API for a website using Yii. I know that there is a utility class called CJson and has a function called encode.

As far as I know there are additional parameters that can be customized in the native json_encode function like the JSON_NUMERIC_CHECK which is really useful. It creates

{
    "id": 17
}

instead of Yii's CJSON encode which makes the '17' a string.

{
    "id": "17"
}

So my question is whether there is any reason I should use CJSON encode instead of the built in PHP function json_encode ?

标签: php json yii
4条回答
Juvenile、少年°
2楼-- · 2019-02-11 11:19

This question is old. I am working with Yii 1.4, PHP 5.4.

The difference i found was 'json_encode' encodes only class properties, while as 'CJSON::encode' encodes only properties listed at the class documentation using @property annotation... This is true at least for CActiveRecord

查看更多
Melony?
3楼-- · 2019-02-11 11:26

Only thing I can think minimum php version support.

Yii support php 5.1 as minimum version See Yii Installation Page . While json_encode/json_decode introduced in php 5.2. So It can be a reason for Yii having a library for CJson.

查看更多
何必那么认真
4楼-- · 2019-02-11 11:42

I realise this is an old topic, but wanted to add another reason.

By doing all JSON encoding through a helper class like CJSON you can override default behavior. For example you can use it to add a token to prevent JSON hijacking.

查看更多
Animai°情兽
5楼-- · 2019-02-11 11:42

In addition to @kuldeep.kamboj, I should say CJSON::encode will treat that 17 as an integer if you define the data type of the value like this:

// PHP
$toBeConverted = array('id' => (int) 17); // or (int) $myInteger

$jsonString = \CJSON::encode($toBeConverted);    

// $jsonString will be:
{
    "id": 17
}
查看更多
登录 后发表回答