PHP – json
http://jsonlint.com/ 判断 json 语法是否正确
PHP到json
$arr1 = array(); $arr1[‘username‘] = ‘test‘; $arr1[‘age‘] = 24; $jsonObj1 = json_encode($arr1); // {"username":"test","age":24}
$arr2 = array(); $arr2[‘member‘][‘one‘][‘username‘] = ‘test1‘; $arr2[‘member‘][‘one‘][‘age‘] = 26; $arr2[‘member‘][‘two‘][‘username‘] = ‘test2‘; $arr2[‘member‘][‘two‘][‘age‘] = 28; $jsonObj2 = json_encode($arr2); // {"member":{"one":{"username":"test1","age":26},"two":{"username":"test2","age":28}}}
class 到json
class test { public $name = "public Name"; protected $ptName = "proctected Name"; private $pName = "private Name"; public function getName() { return $this->name; } } $Obj = new test(); $jj = json_encode($Obj); // {"name":"public Name"} # 只有 public变量
json 到 php 变量类型
$j = ‘{"key": "value"}‘; $v = json_decode($j); var_dump($v); // 是一个 class // object(stdClass)[1] // public ‘key‘ => string ‘value‘ (length=5) $v = json_decode($j, true); var_dump($v); // 数组类型 // array (size=1) // ‘key‘ => string ‘value‘ (length=5)
另一个复杂的json
{ "employees": [ { "firstName":"Bill" , "lastName":"Gates" }, { "firstName":"George" , "lastName":"Bush" }, { "firstName":"Thomas" , "lastName":"Carter" } ] }
$json = ‘{ "employees": [ { "firstName":"Bill" , "lastName":"Gates" }, { "firstName":"George" , "lastName":"Bush" }, { "firstName":"Thomas" , "lastName":"Carter" } ] }‘; $arr = json_decode($json, true); echo $arr[‘employees‘][0][‘firstName‘];
js 解析json
var jsondata = ‘{"arr": [{ "name": "NAME1", "id": "ID1" }, { "name": "NAME2", "id": "ID2" }, ]}‘; var jsonobj = JSON.parse(jsondata); alert(jsonobj.arr[0].name); // NAME1
$members[‘1‘][‘username‘] = ‘admin1‘; $members[‘1‘][‘groupname‘] = ‘admin1‘; $members[‘1‘][‘uid‘] = ‘1‘; $members[‘2‘][‘username‘] = ‘admin2‘; $members[‘2‘][‘groupname‘] = ‘admin2‘; $members[‘2‘][‘uid‘] = ‘2‘; print_r(json_encode($members)); // {"1":{"username":"admin1","groupname":"admin1","uid":"1"}, // "2":{"username":"admin2","groupname":"admin2","uid":"2"},}
alert(res[1][‘username‘]); // 成功 alert(res[‘1‘][‘username‘]); // 成功 alert(res.1.username); // *失败* alert(res.‘1‘.username); // *失败*