【问题标题】:Can't decode JSON from file in PHP无法从 PHP 中的文件中解码 JSON
【发布时间】:2015-06-06 18:38:13
【问题描述】:

我在 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! 有什么问题?

【问题讨论】:

    标签: php arrays json encode


    【解决方案1】:

    问题是您的文件不是有效的 JSON,因为它使用单引号作为字符串并且使用整数作为对象键:

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

    此外,由于 JSON 是一个对象,您应该使用 json_decode($string, true) 将其解码为关联数组。

    根据the JSON spec

    值可以是双引号中的字符串、数字、真假或空值、对象或数组。

    另外,对象键必须是字符串。

    如果您将单引号更改为双引号并编辑 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];
    ?>
    

    【讨论】:

    • 哦,在python中我可以毫无问题地解码,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2017-09-16
    • 2019-10-30
    • 2017-10-20
    相关资源
    最近更新 更多