简体   繁体   English

无法从PHP中的文件解码JSON

[英]Can't decode JSON from file in PHP

I'm having troubles with json_decode in PHP: 我在PHP中遇到json_decode问题:

I have this on file: 我有这个档案:

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

And this is my php code: 这是我的php代码:

<?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! 但是回声返回任何东西,我使用了var_dump,并且我得到了NULL! What's the problem? 有什么问题?

The issue is that your file is not valid JSON since it uses single quotes for strings and has integers as object keys: 问题是您的文件不是有效的JSON,因为它对字符串使用单引号并将整数作为对象键:

{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) . 另外,由于JSON是对象,因此您应该使用json_decode($string, true)将其解码为关联数组。

According to the JSON spec : 根据JSON规范

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. 值可以是带双引号的字符串,也可以是数字,也可以是true或false或null,或者是对象或数组。

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. 如果将单引号更改为双引号,然后编辑PHP的decode_json调用以解码为关联数组,则它应该可以工作。 For example: 例如:

JSON: JSON:

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

PHP: 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];
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM