json_decode在php中的一些無法解析的字串

來源:互聯網
上載者:User

 關於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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.