關於json_decode在php中的一些無法解析的字串,包括以下幾種常見類型。
一、Bug #42186 json_decode() won't work with \l
當字串中含有\l的時候,json_decode是無法解析,測試代碼:
echo "***********json_decode() won't work with \l*************<br/>";$json = '{"stringwithbreak":"line with a \lbreak!"}';var_dump($json);//stringwithbreak":"line with a \lbreak!var_dump(json_decode($json, true));//null
解決辦法:
主要是將\l進行替換,當然如果真的需要‘\l’,我們就必須不使用json_decode進行解析,可以當作當個字元進行提交。
var_dump(str_replace("\\l", "", $json));//stringwithbreak":"line with a break!print_r(json_decode(str_replace("\\l", "", $json), true));//Array ( [stringwithbreak] => line with a break! )
二、Tabs in Javascript strings break json_decode()
當字串中含有tab鍵時,json_decode()無法解析,例如代碼3-1
echo "<br/>***********Tabs in Javascript strings break json_decode()*************<br/>";var_dump(json_decode('{ "abc": 12, "foo": "barbar" }'));
執行後的返回結果為null
解決辦法:
1、當遇到含有tab鍵輸入的字串時,我們應該避免使用json將資料傳到php,然後使用php作為解析。
2、同樣可以使用如下3-2代碼方式進行替換
$myStr = '{ "abc": 12, "foo": "barbar" }';$replaceStr = str_replace("", "\\t", $myStr);var_dump($replaceStr);var_dump(json_decode($replaceStr ));
三、json_decode returns false when leading zeros aren't escaped with double quotes
當json的value值為number類型,而且該number以0開頭,例如代碼4-1
echo "<br/>***********json_decode returns false when leading zeros aren't escaped with double quotes*************<br/>";$noZeroNumber = '{ "test" : 6}';$zeroNumber= '{ "test" : 06}';var_dump(json_decode($noZeroNumber));//object(stdClass)[1] public 'test' => int 6var_dump(json_decode($zeroNumber));//null
或許對於這種問題很少出現,但是一旦出現了,我們就很難去尋找問題的原因。
四、decode chokes on unquoted object keys
當key值沒有使用引號時,會無法解析,例如代碼5-1
echo "<br/>***********decode chokes on unquoted object keys*************<br/>";var_dump(json_decode('{"a":"tan","model":"sedan"}'));//object(stdClass)[1] public 'a' => string 'tan' (length=3) public 'model' => string 'sedan' (length=5)var_dump(json_decode('{a:"tan","model":"sedan"}'));//null