json
概括
http://jsonlint.com/ 判断 json 语法是否正确
[name] = "eric"; [age] = 24 { "name": "eric", "age": 24 } [first][name] = "eric"; [first][age] = 24; [second][name] = "yuanhe"; [second][age] = 24; { "first": { "name": "eric", "age": 24 }, "second": { "name": "yuanhe", "age": 24 } }
数组 { "user": [ { "name": NAME1, "id": ID1, }, { "name": NAME2, "id": ID2, }, ] }
一维数组
$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 类型
class test { public $name = "public Name"; protected $ptName = "proctected Name"; private $pName = "private Name"; public function getName() { return $this->name; } } $testObj = new test(); $jsonObj3 = json_encode($testObj); // {"name":"public Name"} # 只有共有变量
json 到 php 变量类型
$jsonStr = ‘{"key": "value", "key1": "value1"}‘; $jsonArr = json_decode($jsonStr); var_dump($jsonArr); // 对象类型 // object(stdClass)[2] // public ‘key‘ => string ‘value‘ (length=5) // public ‘key1‘ => string ‘value1‘ (length=6) $realJsonArr = json_decode($jsonStr, true); var_dump($realJsonArr); // 数组类型 // array (size=2) // ‘key‘ => string ‘value‘ (length=5) // ‘key1‘ => string ‘value1‘ (length=6)
js 解析 json
var jsondata = "{"arr": [{ "name": "NAME1", "id": "ID1" }, { "name": "NAME2", "id": "ID2" }, ]}"; var jsonobj = JSON.parse(jsondata); alert(jsonobj.arr[0].name); // NAME1
php 和 json
.. $members[‘abc‘][‘name‘] = ‘namename‘; echo json_encode($members); ..
.. $.getJSON(url, data, function(res) { alert(res[‘abc‘][‘name‘]); # 结果是一样的 alert(res.abc.name); # 结果是一样的 }); ..
{"1":{"username":"admin1","groupname":"admin1","uid":"1"}, "2":{"username":"admin2","groupname":"admin2","uid":"2"},} $members[‘1‘][‘username‘] = ‘admin1‘; $members[‘1‘][‘groupname‘] = ‘admin1‘; $members[‘1‘][‘uid‘] = ‘1‘; $members[‘2‘][‘username‘] = ‘admin2‘; $members[‘2‘][‘groupname‘] = ‘admin2‘; $members[‘2‘][‘uid‘] = ‘2‘; alert(res[1][username]); # 成功 alert(res.1.username); # *失败* alert(res.‘1‘.username); # *失败*