您好我有以下问题,在某些情况下,json_decode不起作用,我得到一个空数组如下。
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = (array)json_decode($decoded);
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
$decoded
显示为json字符串,但$ar
为null
。
任何帮助,请帮助我解决这个问题。
答案 0 :(得分:2)
错误发生在JSON
- 奇怪的是在“记事本”和“否”之间的两个空格中。
看起来空格之间存在非标准字符。删除该字符,JSON有效。
<强>无效强>
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
<强>有效强>
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
将来,理想情况下,您可以使用json_encode
来构建JSON
字符串。该函数将自动为您转义任何无效字符。
答案 1 :(得分:1)
您没有在json_decode
中提供第二个参数作为数组返回,而不是对象
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = json_decode($decoded, true); //<-- Now returned as an array, and not an object
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
<强>输出强>
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
答案 2 :(得分:1)
使用您的代码并解码Base64编码的字符串后,您的JSON数据中有一个CHR(13)
ASCII字符,导致JSON根据JSON Lint验证失败。取出该字符会导致JSON正确解析。
解码的JSON数据:
{
"transcript": "- Pasted the text into Notepad no special characters",
"id": 70,
"isActioned": true,
"user_id": 1,
"task_type_id": 1,
"account_id": 21,
"account_name": "TEST",
"event_date": null
}
HEX Editor截图: