簡體   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