JSON分隔符及意义
{} 用于实现对象的包含,对象都包含在大括号中
, 逗号用于分隔对象的不同属性,或者数组的元素
[] 用于存放数组,数组将存放在中括号中
: 用于表示键/值对的值,冒号前为键,冒号后为该键的值
JSON示例
1 { 2 "addressbook":{ 3 "name":"Mary Lebow", 4 "address":{ 5 "street":"5 Main Street", 6 "city":"San Diego,CA", 7 "zip":91912 8 }, 9 "phoneNumbers":[ 10 "619 332-3452", 11 "664 223-4667" 12 ] 13 } 14 }
使用JSON
语法:$json = Zend_Json::encode($phpNative); 说明:其中,参数$phpNative为PHP常见的数据类型,可以是数组、对象或者其他类型的数据。 函数返回值$json为符合JSON格式的一个字符串。
示例:
<?php require_once("Zend/Json.php"); $temp = array( "a"=>0, "b"=>1, "c"=>array( "c-1"=>21, "c-2"=>22, "c-3"=>23, ), "d"=>3 ); $json = Zend_Json::encode($temp); echo "临时数组内容为:"; echo "<pre>"; print_r($temp); echo "</pre>"; echo "转换为JSON格式内容为:"; echo "<pre>"; print_r($json); echo "</pre>";
结果为:
View Code
临时数组内容为: Array ( [a] => 0 [b] => 1 [c] => Array ( [c-1] => 21 [c-2] => 22 [c-3] => 23 ) [d] => 3 ) 转换为JSON格式内容为: {"a":0,"b":1,"c":{"c-1":21,"c-2":22,"c-3":23},"d":3}
将JSON解码为普通数据
语法:$phpNative = Zend_Json::decode($json);
示例:
<?php require_once("Zend/Json.php"); $json = "{ \"addressbook\":{ \"name\":\"zhangsan\", \"address\":{ \"street\":\"Chang an jie\", \"city\":\"BeiJing\", \"zip\":100001 }, \"phoneNumbers\":[ \"010-12345678\", \"010-11111111\" ] } }"; echo "解码前为:"; echo "<pre>"; print_r($json); echo "</pre>"; $native = Zend_Json::decode($json); echo "解码后为:"; echo "<pre>"; print_r($native); echo "</pre>";
输出结果为:
View Code
解码前为: { "addressbook":{ "name":"zhangsan", "address":{ "street":"Chang an jie", "city":"BeiJing", "zip":100001 }, "phoneNumbers":[ "010-12345678", "010-11111111" ] } } 解码后为: Array ( [addressbook] => Array ( [name] => zhangsan [address] => Array ( [street] => Chang an jie [city] => BeiJing [zip] => 100001 ) [phoneNumbers] => Array ( [0] => 010-12345678 [1] => 010-11111111 ) ) )
说明:
在使用此方法对JSON内容进行解码时,可以将其解码为数组,也可以将其解码为对象。
具体有Zend_Json::decode()方法的第二个参数决定。
语法格式如下
$phpNative = Zend_Json::decode($json,Zend_Json::TYPE_OBJECT);
上个例子解码为对象后的结果为
View Code
解码后为: stdClass Object ( [addressbook] => stdClass Object ( [name] => zhangsan [address] => stdClass Object ( [street] => Chang an jie [city] => BeiJing [zip] => 100001 ) [phoneNumbers] => Array ( [0] => 010-12345678 [1] => 010-11111111 ) ) )
小结:
Json的使用还是比较简单的,在接口应用上需要Json。它可以在不同的语言*用。可以灵活的传递数据。作用与XML类似,但是比XML要节省带宽。