PHP的json_encode分析
json的优点就不说了,有个习惯,我在输出json的时候,喜欢用 sprintf 拼成json格式,
前两天被朋友说不标准,必须要用json_encode生成的才是标准的json格式,我当然很郁闷啦,
用了这么多年了,刚知道 这样做不标准,既然说我不标准,那上面才是标准的json格式?
{a : 'abc'}
{'a' : 'abc'}
{a : "abc"}
{"a" : "abc"}
那都知道,只有第四种才是标准的json格式。
我这么做
$ret_json='{"%s":"%s"}';
echo json_encode($ret_json,"a","abc");
必然也符合标准。
既然如此,那我就要刨根问底,json_encode生成的json格式究竟有什么不同?
上代码
static PHP_FUNCTION(json_encode)
{
zval *parameter;
smart_str buf = {0};
long options = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", ¶meter, &options) == FAILURE) {
return;
}
JSON_G(error_code) = PHP_JSON_ERROR_NONE;
php_json_encode(&buf, parameter, options TSRMLS_CC);
ZVAL_STRINGL(return_value, buf.c, buf.len, 1);
smart_str_free(&buf);
}
JSON_G(error_code) = PHP_JSON_ERROR_NONE;
是定义的json错误,该错误可以通过json_last_error函数获取,你用过吗?反正我没用过。
php_json_encode是主要的操作
PHP_JSON_API void php_json_encode(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */
{
switch (Z_TYPE_P(val))
{
case IS_NULL:
smart_str_appendl(buf, "null", 4); //输出NULL
break;
case IS_BOOL:
if (Z_BVAL_P(val)) {
smart_str_appendl(buf, "true", 4);//输出true
} else {
smart_str_appendl(buf, "false", 5);//输出false
}
break;
case IS_LONG:
smart_str_append_long(buf, Z_LVAL_P(val));//输出长整形的值
break;
case IS_DOUBLE:
{
char *d = NULL;
int len;
double dbl = Z_DVAL_P(val);
if (!zend_isinf(dbl) && !zend_isnan(dbl)) {//非无穷尽
len = spprintf(&d, 0, "%.*k", (int) EG(precision), dbl);
smart_str_appendl(buf, d, len);
efree(d);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", dbl);
smart_str_appendc(buf, '0');
}
}
break;
case IS_STRING://字符串
json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options TSRMLS_CC);
break;
case IS_ARRAY://数组和对象
case IS_OBJECT:
json_encode_array(buf, &val, options TSRMLS_CC);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "type is unsupported, encoded as null");
smart_str_appendl(buf, "null", 4);
 
补充:Web开发 , php ,
- 更多JS疑问解答:
- 几个验证11位手机号码格式的js代码
- js如何获得FCKeditor控件的值
- 用js限制投票的cookie .目前设置的为:<input type="" class="" onclick="'window.location...
- JS验证,这块“牛皮”反复修改都不能实现
- 在JS中使用DOM模型
- 如何用JS 获取本地文件夹的文件列表
- js中new 了两个Object数组。怎么样将数组内容合并,重复的内容?
- 求实现自动生成图片缩略图的JS代码
- JS脚本网页问题
- js,代码中"object"和"Object"区别?
- js+flash实现网页图片切换效果,出现边框,单击激活此控件。
- JS怎样操作PHP中的参数
- js 怎么在一打开页面就加载这个函数。
- Date.parse()的问题(js)
- <script src="/{maxcms:sitepath}js/common.js"></script>是什么意思