1 回答

TA貢獻1859條經驗 獲得超6個贊
無效的 JSON
json_decode失敗(無提示)并返回,null因為這不是有效的 JSON 文檔。JSON 不允許在數組的最后一項或對象的最后列出的屬性上使用逗號。你從哪里得到這個 JSON 文檔?這是有效的 Javascript,但不是有效的 JSON。
違規行是:
{
"Artist": "Artist One",
"UUID": "364226",
"Image": "http://theurl.com", <-- remove this in the other objects too
},
和
}
]
}, <-- remove this
],
"nextPageToken": null
}
希望你擁有這個“外部 json 文件”并且可以編輯它,否則就沒有辦法解決它。用json linter檢查你的 json 文件。
錯誤使用嵌套foreach循環
要得到你想要的東西(假設每個項目都是“藝術家”):
foreach($data["items"] as $item){
foreach($item["items"] as $artist){
echo $artist["Artist"];
echo $artist["UUID"];
echo $artist["Image"];
}
}
你不應該foreachJSON 對象的每個屬性,只有那些是可迭代的。
附錄
這是固定的 json 文件,刪除了有問題的逗號:
{
"items": [
{
"title": null,
"itemType": "artist",
"moreTrackingTitle": "All Artists",
"items": [
{
"Artist": "Artist One",
"UUID": "364226",
"Image": "http://theurl.com"
},
{
"Artist": "Artist Two",
"UUID": "1513513",
"Image": "http://theurl.com"
},
{
"Artist": "Artist Three",
"UUID": "214141",
"Image": "http://theurl.com"
}
]
}
],
"nextPageToken": null
}
要強制 PHP 在讀取無效的 JSON 字符串時拋出異常而不是返回 null,請將 JSON_THROW_ON_ERROR 作為第四個參數傳遞:
$data = json_decode(file_get_contents("data.json"), true, 512, JSON_THROW_ON_ERROR);
- 1 回答
- 0 關注
- 153 瀏覽
添加回答
舉報