繁体   English   中英

无法在php中使用json_decode()解析json节点

[英]Not able to parse json node with json_decode() in php

这是我尝试使用json_decode()函数解析的变量中的json字符串。 我正在尝试使用它检索特定的节点信息,但它向我显示了空白的白页。 想要尝试使用file_get_contents()来从外部文件中获取json字符串。 我已经看过以前的问题的答案,但这并没有帮助我

<?php
//$json = file_get_contents('jsonfile.json');
$json = '[
{
    "selfie": {
        "post_author": "2",
        "post_date": "2014-12-02 13:00:00",
        "post_date_gmt": "2014-12-02 13:00:00",
        "post_content": "this is an example content",
        "image": "http://ssomesite.com/webservice/uploads/support.jpg",
        "post_title": "TestJSON"
    }
}
]';
$result = json_decode ($json);
echo $result->selfie->post_date;
//echo $result->selfie;
?>
echo $result[0]->selfie->post_date;

您的对象路径错误。 它应该是

echo $result[0]->selfie->post_date;

...因为JSON以数组开头,因此您的自定义定义位于第一个元素中,因此为[0]

您的JSON格式定义了一个数组,其中包含一个对象,并具有一个名为selfie属性,您需要像这样访问数据:

echo $result[0]->selfie->post_date;

如果曾经无法解析JSON字符串,那么最好的办法就是检查json_last_errorjson_last_error_msg告诉您的问题是什么。

我认为您缺少该父数组。 您还需要考虑数组:

<?php
$json = '[
{
    "selfie": {
        "post_author": "2",
        "post_date": "2014-12-02 13:00:00",
        "post_date_gmt": "2014-12-02 13:00:00",
        "post_content": "this is an example content",
        "image": "http://ssomesite.com/webservice/uploads/support.jpg",
        "post_title": "TestJSON"
    }
}
]';
$result = json_decode ($json);
print($result[0]->selfie->post_date);
?>

演示版

那是一个数组对象。 而不是使用$result->selfie->post_date 采用:

var_dump($result[0]->selfie->post_date);
<?php
//$json = file_get_contents('jsonfile.json');
$json = '[
{
    "selfie": {
        "post_author": "2",
        "post_date": "2014-12-02 13:00:00",
        "post_date_gmt": "2014-12-02 13:00:00",
        "post_content": "this is an example content",
        "image": "http://ssomesite.com/webservice/uploads/support.jpg",
        "post_title": "TestJSON"
    }
}
]';
$result = json_decode ($json,true);
$rs = (array)$result;
echo '<pre>';
print_r($rs);
die;
?>

Array
(
    [0] => Array
        (
            [selfie] => Array
                (
                    [post_author] => 2
                    [post_date] => 2014-12-02 13:00:00
                    [post_date_gmt] => 2014-12-02 13:00:00
                    [post_content] => this is an example content
                    [image] => http://ssomesite.com/webservice/uploads/support.jpg
                    [post_title] => TestJSON
                )

        )

)

经过大量研究后,我发现file_get_contents()实际上是从文件中获取数据,但是由于其编码方式,因此在json之前有一些垃圾字符,例如

因此,为此,我将编码更改为utf8(BOM或不带BOM),现在可以正常使用了。

@ rut2已经回答了同一个文件中带有json字符串的问题,其他开发也是如此。 我感谢他们为解决我的问题所做的努力。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM