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 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低