在json_decode中获取null


Getting null in json_decode

我有一个文本文件上有json。在下面的例子:

{'something' : 'ss'}

我试图在php上读取它并将其转换为使用json_decode的数组。

        $temp = '';
        $fh = fopen( '/quiz' . $testid . '.txt' ,'r');
        while ($line = fgets($fh)) {
            $temp .= $line;
        }
        fclose($fh);
        $temp = str_replace("'n","",$temp); //to remove new line
        $temp = str_replace("'r","",$temp);
        $temp = json_decode($temp);

但我得到null

如果我不json_decode它…我可以得到字符串

我希望有人能帮我这个忙。

谢谢,E

在调用json_decode之前不需要做任何解析

$contents = file_get_contents('/quiz' . $testid . '.txt');
$temp = json_decode($contents);

如果你仍然得到null,你的JSON可能是无效的,你可以使用json_last_error来诊断它

这段代码可以工作所以我认为这是你的文件解析算法的问题

<?php
$temp = '';
$temp='{
"a":1,
"b":[1,2,3]
}';
$temp = str_replace("'n","",$temp); //to remove new line
$temp = str_replace("'r","",$temp);
$temp = json_decode($temp);
var_dump($temp);
?>

如文档所示:

以适当的PHP类型返回json编码的值。值true, false和null返回为true, false和null分别。如果json不能被解码或者返回NULL编码的数据深度超过递归限制。

原因是你没有有效的JSON。

Parse error on line 1:
{    'something': 'ss'}
-----^
Expecting 'STRING', '}'

你的意思可能是:

{
    "something": "ss"
}