YII CJson类
2014-07-26 21:13 youxin 阅读(1529) 评论(0) 编辑 收藏 举报CJson文档:
http://www.yiiframework.com/doc/api/1.1/CJSON
CJson::encode可以编码任何类型的数据:源码如下;
public static function encode($var) { switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; case 'NULL': return 'null'; case 'integer': return (int) $var; case 'double': case 'float': return str_replace(',','.',(float)$var); // locale-independent representation case 'string': if (($enc=strtoupper(Yii::app()->charset))!=='UTF-8') $var=iconv($enc, 'UTF-8', $var); if(function_exists('json_encode')) return json_encode($var); // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT $ascii = ''; $strlen_var = strlen($var); /* * Iterate over every character in the string, * escaping with a slash or encoding to UTF-8 where necessary */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($var{$c}); switch (true) { case $ord_var_c == 0x08: $ascii .= '\b'; break; case $ord_var_c == 0x09: $ascii .= '\t'; break; case $ord_var_c == 0x0A: $ascii .= '\n'; break; case $ord_var_c == 0x0C: $ascii .= '\f'; break; case $ord_var_c == 0x0D: $ascii .= '\r'; break; case $ord_var_c == 0x22: case $ord_var_c == 0x2F: case $ord_var_c == 0x5C: // double quote, slash, slosh $ascii .= '\\'.$var{$c}; break; case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): // characters U-00000000 - U-0000007F (same as ASCII) $ascii .= $var{$c}; break; case (($ord_var_c & 0xE0) == 0xC0): // characters U-00000080 - U-000007FF, mask 110XXXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c+1})); $c+=1; $utf16 = self::utf8ToUTF16BE($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF0) == 0xE0): // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2})); $c+=2; $utf16 = self::utf8ToUTF16BE($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF8) == 0xF0): // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2}), ord($var{$c+3})); $c+=3; $utf16 = self::utf8ToUTF16BE($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFC) == 0xF8): // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2}), ord($var{$c+3}), ord($var{$c+4})); $c+=4; $utf16 = self::utf8ToUTF16BE($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFE) == 0xFC): // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c+1}), ord($var{$c+2}), ord($var{$c+3}), ord($var{$c+4}), ord($var{$c+5})); $c+=5; $utf16 = self::utf8ToUTF16BE($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; } } return '"'.$ascii.'"'; case 'array': /* * As per JSON spec if any array key is not an integer * we must treat the the whole array as an object. We * also try to catch a sparsely populated associative * array with numeric keys here because some JS engines * will create an array with empty indexes up to * max_index which can cause memory issues and because * the keys, which may be relevant, will be remapped * otherwise. * * As per the ECMA and JSON specification an object may * have any string as a property. Unfortunately due to * a hole in the ECMA specification if the key is a * ECMA reserved word or starts with a digit the * parameter is only accessible using ECMAScript's * bracket notation. */ // treat as a JSON object if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { return '{' . join(',', array_map(array('CJSON', 'nameValue'), array_keys($var), array_values($var))) . '}'; } // treat it like a regular array return '[' . join(',', array_map(array('CJSON', 'encode'), $var)) . ']'; case 'object': if ($var instanceof Traversable) { $vars = array(); foreach ($var as $k=>$v) $vars[$k] = $v; } else $vars = get_object_vars($var); return '{' . join(',', array_map(array('CJSON', 'nameValue'), array_keys($vars), array_values($vars))) . '}'; default: return ''; } }
$item = Item::model()->findByPk($_GET['id']);
CJSON::encode($item)。
如果换成json_encode则错误,因为$item类型为CActiveRecord.
我们可以
$item->attributes;得到Returns all column attribute values.
然后才可以使用json_encode。
转一篇文章:
近日在了解YII中的JSON操作方法,发现内置了好几种进行JSON对象和字符串,包括JS的JSON互通的方法,下面是三种方式的JSON解析:上代码
- CJSON::encode( $json );
- json_encode( $json );
- CJavaScript::jsonEncode( $json );
我们还是来看个例子吧!先上代码吧:
- $json = array (
- 'item1' => array (
- 'item11' => array (
- 'n' => 'chenling',
- 'm' => 'llll'
- ),
- 'sex' => '男',
- 'age' => 25,
- 'admin'=>true
- ),
- 'item2' => array (
- 'item21' => 'ling',
- 'sex' => '女',
- 'age' => '24',
- 'admin'=>false
- )
- );
这上面是个三个层级的数组,数组的值包括了字符串、boolean、和数字,我们通过上面的三种方式来输出看看结果是什么:
- $jsonObj = CJSON::encode( $json );
- $jsono = json_encode( $json );
- $jsonjs = CJavaScript::jsonEncode( $json );
- echo $jsonObj.'<br />';
- echo $jsonjs.'<br />';
- echo $jsono.'<br />';
结果:
看来三种方式都可以,解析出来的也是一样的。如果要访问数组的值的话,用下面的 代码就行了。
- echo $json['item1']['sex'].'<br />';
现在来看看转换成JSON对象的方法:
- $jsonstr='{"item1":{"item11":{"n":"chenling","m":"llll"},"sex":"男","age":"25"},"item2":{"item21":"ling","sex":"女","age":"24"}}';
- echo $jsonstr.'<br />';
- //$j = CJSON::decode($jsonstr);
- //$j = CJavaScript::jsonDecode($jsonstr);
- <span style="color:#ff0000;"><strong>$j = json_decode($jsonstr,true);//当字符串为{"1":1,"2":1} 这种模式时,json_decode默认解析出来的结果是一个对象,此时可以设置它的第二个参数为true强制让它返回数组</strong></span>
上面两个方法转换都是没有问题的,关键是上面红色标注的就有问题了,如果我没有加后面的参数true的话,结果就是下面的报错信息,原因就是因为
当字符串为{"1":1,"2":1} 这种模式时,json_decode默认解析出来的结果是一个对象,此时可以设置它的第二个参数为true强制让它返回数组。
如果是下面的这个代码,则转换就没有问题
- $jsonstr = '[1,2,3]';
- $j = json_decode($jsonstr);//如果不加第二个参数的话,当字符串为[1,2,3] 这种模式时,json_decode默认解析出来的结果是一个数组
- echo $j[2].'<br />';
所以这个是要注意的,同时我们可能遇到下面的这种情况的JSON字符串,这个也是要注意的!尤其是要注意转换完成后的数组访问方式:
- $jsonstr='{"item1":[{"name":[{"chen":"chenling","ling":"chenli"}],"sex":"男","age":"25"},{"name":"sun","sex":"女","age":"24"}]}';
- $j = CJSON::decode($jsonstr);
- echo $j['item1'][0]['name'][0]['chen'].'<br />';
- <strong><span style="color:#ff0000;">$j = json_decode($jsonstr,true);</span></strong>
- echo $j['item1'][0]['name'][0]['chen'].'<br />';
- $j = CJavaScript::jsonDecode($jsonstr);
- echo $j['item1'][0]['name'][0]['chen'].'<br />';
这种情况也得注意,都是数组的情况下,只能通过索引进行访问,而不能通过key来访问。
- $jsonstr='[["item1","item11"],["n","chenling"],["m","llll"]]';
- $j = CJSON::decode($jsonstr);
- echo $j[1][1].'<br />';
- $j = json_decode($jsonstr);
- echo $j[0][0].'<br />';
- $j = CJavaScript::jsonDecode($jsonstr);
- echo $j[0][0].'<br />';
也就是说在这三种的情况下:
CJSON和CJavaScript的方式是可以通用的,而json_的方式是需要第二个参数来决定的。所以为了兼容,我们还是尽量使用前两个进行JSON的转换操作;
转自: http://blog.csdn.net/qq415734794/article/details/7662449