dougan7523 2015-06-06 18:38
浏览 49
已采纳

无法从PHP中的文件解码JSON

I'm having troubles with json_decode in PHP:

I have this on file:

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

And this is my php code:

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

But the echo returns anything, I used var_dump, and I get NULL! What's the problem?

  • 写回答

1条回答 默认 最新

  • dongtou8736 2015-06-06 18:41
    关注

    The issue is that your file is not valid JSON since it uses single quotes for strings and has integers as object keys:

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

    Also, since the JSON is an object, you should decode it to an associative array using json_decode($string, true).

    According to the JSON spec:

    A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.

    Also, the object keys need to be strings.

    If you change the single quotes to double quotes and edit your PHP's decode_json call to decode to an associative array, it should work. For example:

    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];
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要