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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line