簡體   English   中英

無法從PHP中的文件解碼JSON

[英]Can't decode JSON from file in PHP

我在PHP中遇到json_decode問題:

我有這個檔案:

{1: ['oi','oi'], 2: ['foo','bar']}

這是我的php代碼:

<?php 
    $string = file_get_contents("quizen.json"); // the file
    $json = json_decode($string);
    echo $json[1][0]
?>

但是回聲返回任何東西,我使用了var_dump,並且我得到了NULL! 有什么問題?

問題是您的文件不是有效的JSON,因為它對字符串使用單引號並將整數作為對象鍵:

{1: ['oi','oi'], 2: ['foo','bar']}

另外,由於JSON是對象,因此您應該使用json_decode($string, true)將其解碼為關聯數組。

根據JSON規范

值可以是帶雙引號的字符串,也可以是數字,也可以是true或false或null,或者是對象或數組。

同樣,對象鍵必須是字符串。

如果將單引號更改為雙引號,然后編輯PHP的decode_json調用以解碼為關聯數組,則它應該可以工作。 例如:

JSON:

{"1": ["oi","oi"], "2": ["foo","bar"]}

PHP:

<?php 
    $string = file_get_contents("quizen.json"); // the file
    $json = json_decode($string, true); // set to true for associative array
    echo $json["1"][0];
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM