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

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器