php - 无法从 PHP 文件中解码 JSON

标签 php arrays json encode

我在 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]
?>

但是 echo 返回任何内容,我使用了 var_dump,并且得到 NULL! 有什么问题吗?

最佳答案

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

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

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

根据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.

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

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

关于php - 无法从 PHP 文件中解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686319/

相关文章:

可以从 PHP 动态生成多个按钮的 Javascript

php - 在php mysql中加入4个表

ruby-on-rails - I18n 数组中的插值

php - 在子组中分组(使用 php 循环)

ios - 如何使用新的 Apple Swift 语言发布 JSON

php - 如何在mysql连接失败时打开缓存?

PHP MongoDB 从结果中排除 _id

c# - 遍历数组并找到部分字符串

javascript - 如何通过 Angular js将json从指令传递到 Controller

json - 获取自下而上的嵌套json以在postgresql中进行查询