一、json_decode的簡介
json_decode是php函數庫中一個非常常用的函數,它可以將符合json格式的字符串轉換成php的對象或者數組。
json是一種輕量級的數據交換格式,以其速度快、易讀、易解析等優點廣泛應用於前後端的數據傳輸中。而json_decode函數提供了一種簡便有效的方法將json字符串轉換為php對象或數組,從而方便php處理json數據。
$jsonStr = '{"name":"小明","age":20}'; $obj = json_decode($jsonStr); //將json字符串轉換成php對象 $arr = json_decode($jsonStr,true); //將json字符串轉換成php數組
上述示例演示了如何將json字符串轉換成php對象或數組,並且可以根據需要選擇將轉換的對象是數組還是對象。
二、json_decode的參數解析
json_decode函數提供了兩個參數,分別為待轉換的json字符串和一個bool類型的參數$assoc。當$assoc為true時,將返回php關聯數組,否則返回php對象。
如果不需要轉換成關聯數組,可以使用默認情況下的false,將json字符串轉換成php對象。如果需要轉換成數組,將第二個參數設置為true即可。
$jsonStr = '{"name":"小明","age":20,"scores":[98,86,75]}'; $obj = json_decode($jsonStr); $arr = json_decode($jsonStr,true); echo $obj->name; //"小明" echo $arr['scores'][0]; //98
三、json_decode的返回值解析
json_decode的返回值有三種情況,分別是成功返回對象或數組、失敗返回null、部分失敗返回之前成功的部分對象或數組。
當json_decode函數成功轉換後,返回值為既定格式的對象或數組。如果json字符串錯誤,返回null。如果在解析過程中部分錯誤,則可以使用json_last_error函數獲取上一個json解析過程中的錯誤信息。
$jsonStr1 = '{"name":"小明","age":20}'; $obj1 = json_decode($jsonStr1); var_dump($obj1); // object(stdClass)#1 (2) { ["name"]=> string(6) "小明" ["age"]=> int(20) } $jsonStr2 = '{"name":"小明","age":}'; $obj2 = json_decode($jsonStr2); var_dump($obj2); // NULL $jsonStr3 = '{"name":"小明","age":20,"scores":[98,86,75}'; $obj3 = json_decode($jsonStr3); var_dump($obj3); // object(stdClass)#3 (2) { ["name"]=> string(6) "小明" ["age"]=> int(20) } echo json_last_error(); // 4 (意味着json解析字符串不合法)
四、json_decode的擴展
在實際應用中,json_decode函數有時候不能直接滿足我們的需求,因此我們需要用到一些擴展的功能,這裡介紹json_decode的兩個比較常用的擴展。
1、json_decode返回指定類型
json_decode函數默認返回的是php對象或數組,如果需要返回其他類型,可以自定義一個decodeJson函數,並在其中設置返回值類型。
function decodeJson($jsonStr,$toarray=false){ if($toarray) { $result = json_decode($jsonStr,true); }else { $result = json_decode($jsonStr); } if($result === null && json_last_error()!==JSON_ERROR_NONE) { throw new \Exception("Failed to parse JSON: ".json_last_error_msg()); } return $result; } $obj = decodeJson('{"name":"小明","age":20}'); //返回php對象 $arr = decodeJson('{"name":"小明","age":20,"scores":[98,86,75]}',true); //返回php數組
2、處理json_decode轉換失敗的情況
在實際應用中,json字符串可能並不總是符合格式要求,因此需要對json_decode函數進行一定的封裝,防止json字符串格式錯誤導致的服務中斷。
function tryDecodeJson($jsonStr,$default=null){ if(is_string($jsonStr)){ try{ $result = json_decode($jsonStr,true); if(json_last_error()==JSON_ERROR_NONE) { return $result; } }catch(\Exception $e){ return $default; } } return $default; } $obj = tryDecodeJson('{"name":"小明","age":20}'); //返回php對象或null $arr = tryDecodeJson('{"name":"小明","age":20,"scores":[98,86,75x]}',[]); //返回php數組或默認值[]
五、小結
json_decode函數是php中一個非常重要常用的函數,可以幫助我們將符合特定格式的字符串轉化成php的對象或數組。在實際應用中,我們可能會根據需求進行調整,擴展json_decode的功能,如返回指定類型的對象或數組,或者對json_decode解析失敗進行處理等。我們通過本篇文章的學習,也深入了解了json_decode函數的使用,以及一些基礎的錯誤處理姿勢。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/242071.html