目前,JSON已經成為最流行的數據交換格式之一,各大網站的API幾乎都支持它。
我寫過一篇《數據類型和JSON格式》,探討它的設計思想。今天,我想總結一下PHP語言對它的支持,這是開發互聯網應用程序(特別是編寫API)必須了解的知識。
從5.2版本開始,PHP原生提供json_encode()和json_decode()函數,前者用於編碼,後者用於解碼。
一、json_encode()
該函數主要用來將數組和對象,轉換為json格式。先看一個數組轉換的例子:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr);
結果為
{"a":1,"b":2,"c":3,"d":4,"e":5}
再看一個對象轉換的例子:
$obj->body = 'another post'; $obj->id = 21; $obj->approved = true; $obj->favorite_count = 1; $obj->status = NULL; echo json_encode($obj);
結果為
{ "body":"another post", "id":21, "approved":true, "favorite_count":1, "status":null }
由於json只接受utf-8編碼的字符,所以json_encode()的參數必須是utf-8編碼,否則會得到空字符或者null。當中文使用GB2312編碼,或者外文使用ISO-8859-1編碼的時候,這一點要特別注意。
二、索引數組和關聯數組
PHP支持兩種數組,一種是只保存"值"(value)的索引數組(indexed array),另一種是保存"名值對"(name/value)的關聯數組(associative array)。
由於javascript不支持關聯數組,所以json_encode()只將索引數組(indexed array)轉為數組格式,而將關聯數組(associative array)轉為對象格式。
比如,現在有一個索引數組
$arr = Array('one', 'two', 'three'); echo json_encode($arr);
結果為:
["one","two","three"]
如果將它改為關聯數組:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three'); echo json_encode($arr);
結果就變了:
{"1":"one","2":"two","3":"three"}
注意,數據格式從"[]"(數組)變成了"{}"(對象)。
如果你需要將"索引數組"強制轉化成"對象",可以這樣寫
json_encode( (object)$arr );
或者
json_encode ( $arr, JSON_FORCE_OBJECT );
三、類(class)的轉換
下面是一個PHP的類:
class Foo { const ERROR_CODE = '404'; public $public_ex = 'this is public'; private $private_ex = 'this is private!'; protected $protected_ex = 'this should be protected'; public function getErrorCode() { return self::ERROR_CODE; } }
現在,對這個類的實例進行json轉換:
$foo = new Foo; $foo_json = json_encode($foo); echo $foo_json;
輸出結果是
{"public_ex":"this is public"}
可以看到,除了公開變量(public),其他東西(常量、私有變量、方法等等)都遺失了。
四、json_decode()
該函數用於將json文本轉換為相應的PHP數據結構。下面是一個例子:
$json = '{"foo": 12345}'; $obj = json_decode($json); print $obj->{'foo'}; // 12345
通常情況下,json_decode()總是返回一個PHP對象,而不是數組。比如:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json));
結果就是生成一個PHP對象:
object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
如果想要強制生成PHP關聯數組,json_decode()需要加一個參數true:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json,true));
結果就生成了一個關聯數組:
array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
五、json_decode()的常見錯誤
下面三種json寫法都是錯的,你能看出錯在哪裡嗎?
$bad_json = "{ 'bar': 'baz' }"; $bad_json = '{ bar: "baz" }'; $bad_json = '{ "bar": "baz", }';
對這三個字符串執行json_decode()都將返回null,並且報錯。
第一個的錯誤是,json的分隔符(delimiter)只允許使用雙引號,不能使用單引號。第二個的錯誤是,json名值對的"名"(冒號左邊的部分),任何情況下都必須使用雙引號。第三個的錯誤是,最後一個值之後不能添加逗號(trailing comma)。
另外,json只能用來表示對象(object)和數組(array),如果對一個字符串或數值使用json_decode(),將會返回null。
var_dump(json_decode("Hello World")); //null
下面給大家介紹哦php語言的json實現
由於開發一個ajax file manager for web開源項目,數據交換使用的json格式,後來發現在低版本的php上運行會有問題,仔細調試發現json_decode和json_encode無法正常工作,於是查閱資料,發現低版本的php沒有實現這兩個函數,為了兼容性,我只好自己實現一個php版的json編碼解碼代碼,並保證和json2.js的一致,測試調試並通過,現在將其公布出來,供有相同需求的同學使用:
<?php /* * **************************************************************************** * $base: $ * * $Author: $ * Berlin Qin * * $History: base.js $ * Berlin Qin // created * * $contacted * [email protected] * www.webfmt.com * * *************************************************************************** */ /* =========================================================================== * license * * 、Open Source Licenses * webfmt is distributed under the GPL, LGPL and MPL open source licenses. * This triple copyleft licensing model avoids incompatibility with other open source licenses. * These Open Source licenses are specially indicated for: * Integrating webfmt into Open Source software; * Personal and educational use of webfmt; * Integrating webfmt in commercial software, * taking care of satisfying the Open Source licenses terms, * while not able or interested on supporting webfmt and its development. * * 、Commercial License – fbis source Closed Distribution License - CDL * For many companies and products, Open Source licenses are not an option. * This is why the fbis source Closed Distribution License (CDL) has been introduced. * It is a non-copyleft license which gives companies complete freedom * when integrating webfmt into their products and web sites. * This license offers a very flexible way to integrate webfmt in your commercial application. * These are the main advantages it offers over an Open Source license: * Modifications and enhancements doesn't need to be released under an Open Source license; * There is no need to distribute any Open Source license terms alongside with your product * and no reference to it have to be done; * No references to webfmt have to be done in any file distributed with your product; * The source code of webfmt doesn't have to be distributed alongside with your product; * You can remove any file from webfmt when integrating it with your product. * The CDL is a lifetime license valid for all releases of webfmt published during * and before the year following its purchase. * It's valid for webfmt releases also. It includes year of personal e-mail support. * * ************************************************************************************************************************************************* */ function jsonDecode($json) { $result = array(); try { if (PHP_VERSION_ID > ) { $result = (array) json_decode($json); } else { $json = str_replace(array("\\\\", "\\\""), array("", ""), $json); $parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); foreach ($parts as $index => $part) { if (strlen($part) == ) { switch ($part) { case "[": case "{": $parts[$index] = "array("; break; case "]": case "}": $parts[$index] = ")"; break; case ":": $parts[$index] = "=>"; break; case ",": break; default: break; } } } $json = str_replace(array("", "", "$"), array("\\\\", "\\\"", "\\$"), implode("", $parts)); $result = eval("return $json;"); } } catch (Exception $e) { $result = array("error" => $e->getCode()); } return $result; } function valueTostr($val) { if (is_string($val)) { $val = str_replace('\"', "\\\"", $val); $val = str_replace("\\", "\\\\", $val); $val = str_replace("/", "\\/", $val); $val = str_replace("\t", "\\t", $val); $val = str_replace("\n", "\\n", $val); $val = str_replace("\r", "\\r", $val); $val = str_replace("\b", "\\b", $val); $val = str_replace("\f", "\\f", $val); return '"' . $val . '"'; } elseif (is_int($val)) return sprintf('%d', $val); elseif (is_float($val)) return sprintf('%F', $val); elseif (is_bool($val)) return ($val ? 'true' : 'false'); else return 'null'; } function jsonEncode($arr) { $result = "{}"; try { if (PHP_VERSION_ID > ) { $result = json_encode($arr); } else { $parts = array(); $is_list = false; if (!is_array($arr)) { $arr = (array) $arr; } $end = count($arr) - ; if (count($arr) > ) { if (is_numeric(key($arr))) { $result = "["; for ($i = ; $i < count($arr); $i++) { if (is_array($arr[$i])) { $result = $result . jsonEncode($arr[$i]); } else { $result = $result . valueTostr($arr[$i]); } if ($i != $end) { $result = $result . ","; } } $result = $result . "]"; } else { $result = "{"; $i = ; foreach ($arr as $key => $value) { $result = $result . '"' . $key . '":'; if (is_array($value)) { $result = $result . jsonEncode($value); } else { $result = $result . valueTostr($value); } if ($i != $end) { $result = $result . ","; } $i++; } $result = $result . "}"; } } else { $result = "[]"; } } } catch (Exception $e) { } return $result; } ?>
如果使用過程有什麼問題,可以給我email.歡迎大家指出錯誤!