我首先要说我对使用 php 和 JSON 很陌生,所以如果我犯了任何愚蠢的错误,请善待。:)
我正在尝试读取保存在我的服务器上的 JSON 文件。当我尝试执行 json_decode() 时,它返回 null。我相信这与文件创建时的换行或格式有关,因为如果我执行以下操作:
$json_string = '{"tomorrow":"2018-09-15"}';
那么解码工作正常。我在制作 JSON 文件时做错了什么,还是我需要对文件做一些额外的事情以使其与解码兼容?现在已经为此工作了几天,这让我发疯。对此的任何指导将不胜感激。
这是我的php代码:
$filePath = 'test.json';
$json_string = file_get_contents($filePath);
//$json_string = '{"tomorrow":"2018-09-15"}';
$json_string = str_replace("\\n", "", $json_string);
var_dump(json_encode($json_string));
//ShowDebug("Test1:" . $json_string);
//$json_string = '{"foo-bar": 12345}'
$json = json_decode($json_string ,true);
var_dump(json_decode($json_string ,true));
switch (json_last_error()) {
case JSON_ERROR_NONE:
ShowDebug(' - No errors');
break;
case JSON_ERROR_DEPTH:
ShowDebug(' - Maximum stack depth exceeded');
break;
case JSON_ERROR_STATE_MISMATCH:
ShowDebug(' - Underflow or the modes mismatch');
break;
case JSON_ERROR_CTRL_CHAR:
ShowDebug(' - Unexpected control character found');
break;
case JSON_ERROR_SYNTAX:
ShowDebug(' - Syntax error, malformed JSON');
break;
case JSON_ERROR_UTF8:
ShowDebug(' - Malformed UTF-8 characters, possibly incorrectly encoded');
break;
default:
ShowDebug(' - Unknown error');
break;
}
foreach ($json as $value)
{
ShowDebug("Testing: $value->tomorrow");
}
这是我的测试 JSON 文件:
[
{
"Test": "hello",
"Test2": "Hi"
},
{
"Test": "Goodbye",
"Test2": "Bye"
}
]
这是在 php 文件中使用 JSON 时编码和解码的 var 转储:
string(31) ""{\"tomorrow\":\"2018-09-15\"}"" <---- This is the var dump of encode
array(1) {
["tomorrow"]=> <--- This is the var dump of decode
string(10) "2018-09-15"
}
这是使用另一个文件中的 JSON 时编码和解码的另一个 var 转储:
string(202) ""[\r\n {\r\n \\\"Test\\\": \\\"hello\\\",\r\n \\\"Test2\\\": \\\"Hi\\\"\r\n },\r\n {\r\n \\\"Test\\\": \\\"Goodbye\\\",\r\n \\\"Test2\\\": \\\"Bye\\\"\r\n }\r\n]"" <--- This is encode
NULL <--- This is decode
编辑:根据评论更新
我从 var 转储中删除了编码,并删除了字符串替换,新的输出是:
string(150) "[
{
\"Test\": \"hello\",
\"Test2\": \"Hi\"
},
{
\"Test\": \"Goodbye\",
\"Test2\": \"Bye\"
}
]"
NULL