遇到js传给PHP端一个json数据,json_decode无法解析返回null,用json_last_error返回错误码,发现是语法错误!费了半天劲查找原因!原来是key,value没有加上双引号,还有数据中使用了单引号这两个原因导致php无法解析。
话不多,直接上解决方法!
方法如下:
<?php
$json = "{
id : 'root',
item : [{
id : 001,
text : \"根节点\",
open : 'true',
item : [{
id : 1,
text : \"first\",
item : [{
id : \"c1\",
text : \"child1\"
}
]
}, {
id : 2,
text : \"middle\",
item : [{
id : \"c2\",
text : \"child2\",
item : [{
id : \"c1-1\",
text : \"testChild\"
}
]
}, {
id : \"c3\",
text : \"child3\"
}
]
}, {
id : 3,
text : \"last\"
}
]
}
]
}";
$json = str_replace('\'', '"', $json);
$json = preg_replace('/\s/', "", $json);
$json = preg_replace('/([\w_0-9]+):/', '"\1":',$json);
$json = preg_replace('/:([^\[|{|"][\d.]+)/', ':"\1"', $json);
print_r(json_decode($json, true));
exit;
?>
---------- php ----------
Array
(
[id] => root
[item] => Array
(
[0] => Array
(
[id] => 001
[text] => 根节点
[open] => true
[item] => Array
(
[0] => Array
(
[id] => 1
[text] => first
[item] => Array
(
[0] => Array
(
[id] => c1
[text] => child1
)
)
)
[1] => Array
(
[id] => 2
[text] => middle
[item] => Array
(
[0] => Array
(
[id] => c2
[text] => child2
[item] => Array
(
[0] => Array
(
[id] => c1-1
[text] => testChild
)
)
)
[1] => Array
(
[id] => c3
[text] => child3
)
)
)
[2] => Array
(
[id] => 3
[text] => last
)
)
)
)
)
输出完成 (耗时 0 秒) - 正常终止