php json_decode null ,转

How To Parse JSON With PHP

------网上找的------------

在网上找了很多,都写的例子是json_encode.我把我遇到的这个情况写下吧!

【第一种情况】json_decode 之后什么都没有,. 原因之一json_decode只支持utf-8.

iconv('gbk','utf-8', $result_string),用iconv函数改变的编码格式,我个案是gbk..转成utf-8.

【第二个情况】 数组对象是需要用print_r ,不能用echo的。

【第三个情况】 之后还有乱码情况 ..我的个案是这样的.

header("Content-Type: text/html; charset=UTF-8");

【其他情况】

http://php.net/manual/en/function.json-decode.php (我在网上下载的php manual chm中竟然 没有写这些.真无语... ) 中有写到:

Example #3 common mistakes using json_decode() 一些大家常常常常常常常常常常常常常常犯的错误.. 其他几个例子也可以看看...

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes 1.这里是说不要使用单引号,正确应该是 $bad_json = '{ "bar": "baz" }';

// single quotes are not valid

$bad_json = "{ 'bar': 'baz' }";

json_decode($bad_json); // null

// the name must be enclosed in double quotes 2.这里是说 名称应该要用""包含起来.. 正确的应该是 $bad_json = '{ "bar": "baz" }';就光这个浪费我好几个小时....弄了半天...哎...

$bad_json = '{ bar: "baz" }';

json_decode($bad_json); // null

// trailing commas are not allowed 3.这里是说 最后一个不需要逗号.

$bad_json = '{ bar: "baz", }';

json_decode($bad_json); // null

?>

如果我们使用 json_encode() 给含有中文的内容进行编码时,会出现类似于\u5c71\u4e1c这样的代码,虽然使用jQuery或者json_decode()进行解码的时候,并不会出现问题,但某些时候,我们还是需要将中文原样的显示出来。

<?php

$code= json_encode($str);

$code= preg_replace("#\\\u([0-9a-f]+)#ie","iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))",$code);

?>