Json解码和变量

时间:2014-03-06 14:13:30

标签: php json

我有

$string = $_REQUEST['COM_node'];

它包含字符串

{"cmp_class":"ProfileReferences","auto_id":"cmp14","forms":[],"parent":{"cmp_class":"PrivateMediaNetworkList","auto_id":"httpdoc"}}

当我尝试

$nodeArray      = json_decode($string, true); 

返回NULL。但是,当我给出像

$string = '{"cmp_class":"ProfileReferences","auto_id":"cmp14","forms":[],"parent":{"cmp_class":"PrivateMediaNetworkList","auto_id":"httpdoc"}}';
$nodeArray      = json_decode($string, true); 

工作正常。我用Google搜索但没有解决方案。请帮帮我。

2 个答案:

答案 0 :(得分:1)

您确定$ _REQUEST ['COM_node']包含没有任何隐藏字符(如UTF-8 BOM或类似字符)的确切字符串吗?

$string = chr(239).chr(187).chr(191).'{"cmp_class":"ProfileReferences","auto_id":"cmp14","forms":[],"parent":{"cmp_class":"PrivateMediaNetworkList","auto_id":"httpdoc"}}';
var_dump($string); // returns your string, although there are hidden chars

$nodeArray = json_decode($string,true);
var_dump($nodeArray); // returns NULL

尝试将其与以下内容进行比较:

$string = '{"cmp_class":"ProfileReferences","auto_id":"cmp14","forms":[],"parent":{"cmp_class":"PrivateMediaNetworkList","auto_id":"httpdoc"}}';
var_dump($_REQUEST['COM_node'] == $string);

如果结果为false,则需要找出要剪掉的字符。

编辑: 您可以修改字符串以仅获取以第一个{并以最后一个结尾}

开头的部分
preg_match("/{(.*)}/",$string,$matches);
$string = $matches[0]; 

答案 1 :(得分:0)

true作为第二个参数传递给json_decode()会返回一个数组。您必须使用print_r()进行查看; echo()无效。

php > $string = '{"cmp_class":"ProfileReferences","auto_id":"cmp14","forms":[],"parent":{"cmp_class":"PrivateMediaNetworkList","auto_id":"httpdoc"}}';
php > echo json_decode($string, true);
PHP Notice: Array to string conversion in php shell code on line 1

php > print_r($json_decode($string, true));
Array
(
    [cmp_class] => ProfileReferences
    [auto_id] => cmp14
    [forms] => Array
        (
        )

    [parent] => Array
        (
            [cmp_class] => PrivateMediaNetworkList
            [auto_id] => httpdoc
        )
)