我知道這個問題很老,但我希望這可以幫助別人。
我有一個類似的問題,因爲我想接受JSON作爲用戶輸入,但不想在每個按鍵周圍都需要繁瑣的「引號」。此外,我不想要求引用值,但仍然解析有效數字。
最簡單的方法似乎是編寫自定義分析器。
我想出了這一點,這解析嵌套關聯/索引的數組:
function loose_json_decode($json) {
$rgxjson = '%((?:\{[^\{\}\[\]]*\})|(?:\[[^\{\}\[\]]*\]))%';
$rgxstr = '%("(?:[^"\\\\]*|\\\\\\\\|\\\\"|\\\\)*"|\'(?:[^\'\\\\]*|\\\\\\\\|\\\\\'|\\\\)*\')%';
$rgxnum = '%^\s*([+-]?(\d+(\.\d*)?|\d*\.\d+)(e[+-]?\d+)?|0x[0-9a-f]+)\s*$%i';
$rgxchr1 = '%^'.chr(1).'\\d+'.chr(1).'$%';
$rgxchr2 = '%^'.chr(2).'\\d+'.chr(2).'$%';
$chrs = array(chr(2),chr(1));
$escs = array(chr(2).chr(2),chr(2).chr(1));
$nodes = array();
$strings = array();
# escape use of chr(1)
$json = str_replace($chrs,$escs,$json);
# parse out existing strings
$pieces = preg_split($rgxstr,$json,-1,PREG_SPLIT_DELIM_CAPTURE);
for($i=1;$i<count($pieces);$i+=2) {
$strings []= str_replace($escs,$chrs,str_replace(array('\\\\','\\\'','\\"'),array('\\','\'','"'),substr($pieces[$i],1,-1)));
$pieces[$i] = chr(2) . (count($strings)-1) . chr(2);
}
$json = implode($pieces);
# parse json
while(1) {
$pieces = preg_split($rgxjson,$json,-1,PREG_SPLIT_DELIM_CAPTURE);
for($i=1;$i<count($pieces);$i+=2) {
$nodes []= $pieces[$i];
$pieces[$i] = chr(1) . (count($nodes)-1) . chr(1);
}
$json = implode($pieces);
if(!preg_match($rgxjson,$json)) break;
}
# build associative array
for($i=0,$l=count($nodes);$i<$l;$i++) {
$obj = explode(',',substr($nodes[$i],1,-1));
$arr = $nodes[$i][0] == '[';
if($arr) {
for($j=0;$j<count($obj);$j++) {
if(preg_match($rgxchr1,$obj[$j])) $obj[$j] = $nodes[+substr($obj[$j],1,-1)];
else if(preg_match($rgxchr2,$obj[$j])) $obj[$j] = $strings[+substr($obj[$j],1,-1)];
else if(preg_match($rgxnum,$obj[$j])) $obj[$j] = +trim($obj[$j]);
else $obj[$j] = trim(str_replace($escs,$chrs,$obj[$j]));
}
$nodes[$i] = $obj;
} else {
$data = array();
for($j=0;$j<count($obj);$j++) {
$kv = explode(':',$obj[$j],2);
if(preg_match($rgxchr1,$kv[0])) $kv[0] = $nodes[+substr($kv[0],1,-1)];
else if(preg_match($rgxchr2,$kv[0])) $kv[0] = $strings[+substr($kv[0],1,-1)];
else if(preg_match($rgxnum,$kv[0])) $kv[0] = +trim($kv[0]);
else $kv[0] = trim(str_replace($escs,$chrs,$kv[0]));
if(preg_match($rgxchr1,$kv[1])) $kv[1] = $nodes[+substr($kv[1],1,-1)];
else if(preg_match($rgxchr2,$kv[1])) $kv[1] = $strings[+substr($kv[1],1,-1)];
else if(preg_match($rgxnum,$kv[1])) $kv[1] = +trim($kv[1]);
else $kv[1] = trim(str_replace($escs,$chrs,$kv[1]));
$data[$kv[0]] = $kv[1];
}
$nodes[$i] = $data;
}
}
return $nodes[count($nodes)-1];
}
注意其不捕獲錯誤或不良格式...
對於您的情況,它看起來像你想添加周圍{}
的(如json_decode
還要求):
$data = loose_json_decode('{' . $json . '}');
這對我產生了:
array(6) {
["id"]=>
int(43015)
["name"]=>
string(8) "John Doe"
["level"]=>
int(15)
["systems"]=>
array(1) {
[0]=>
array(5) {
["t"]=>
int(6)
["glr"]=>
int(1242)
["n"]=>
string(6) "server"
["s"]=>
int(185)
["c"]=>
int(9)
}
}
["classs"]=>
int(0)
["subclass"]=>
int(5)
}
我不相信數字在JSON中需要引號 – 2009-10-15 21:31:46
但是「鍵」確實是,不是嗎?像id:43015應該是「id」:43015,對吧? – hookedonwinter 2009-10-15 21:37:50
是的,問題是沒有引用像「id」這樣的密鑰名稱 – 2009-10-15 21:39:25