關於JSON的優勢:javascript
1、基於純文本,跨平臺傳遞極其簡單;php
2、Javascript原生支持,後臺語言幾乎所有支持;css
3、輕量級數據格式,佔用字符數量極少,特別適合互聯網傳遞;html
4、可讀性較強java
5、容易編寫和解析,json
一,phpjoson數據數組
PHP支持兩種數組,一種是隻保存"值"(value)的索引數組(indexed array),另外一種是保存"名值對"(name/value)的關聯數組(associative array)。spa
json數據的格式有對象和數組,大括號{}和方括號[],其他英文冒號:是映射符,英文逗號,是分隔符,英文雙引號""是定義符。code
對象:htm
1.是一個無序的「‘名稱/值’對」集合
2.以 「{」 (左括號)開始,「}」(右括號)結束
3.每一個「名稱」後跟一個「:」(冒號)
4.多個 」名稱」:」值」 之間使用 ,(逗號)分隔
5.例如:{「username」:」chenshishuo」,」sex」:」man」,」age」:」22」}
數組:
1.值(value)的有序集合
2.以「[」(左中括號)開始,「]」(右中括號)結束
3.值之間使用「,」(逗號)分隔
4.例如:[「a」,」b」,」c」,」d」]
//json_encode()
1)數組是索引數組
那麼輸出的是
2)數組是關聯數組
那麼輸出的是
注意,數據格式從"[]"(數組)變成了"{}"(對象)。
3)轉化類
輸出的是
能夠看到,除了公開變量(public),其餘東西(常量、私有變量、方法等等)都遺失了。
//json_decode
1.鍵值對json數組
1)運行出來後獲得一個對象
若是要取得這個對象的某個值能夠用
$objJson = json_decode($json);
$objJson->a; //輸入 hello
2)若是要用json_decode(「鍵值對json數據」) 返回的是一個數組
則須要加一個參數
json_decode($json,true);
2.非鍵值對的json數據
運行出來後獲得的是一個數組
二.javascript json數據
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <script type="text/javascript"> 8 window.onload = function(){ 9 10 var test = { 11 "a": "hello", 12 "b": "world", 13 "c": 22, 14 "d": true 15 } 16 17 var testone = test.c; 18 alert("第一次"+testone); 19 20 var testmore = [ 21 { 22 "a": "hello", 23 "b": "world", 24 "c": 22, 25 "d": true 26 }, 27 { 28 "a": "hello2", 29 "b": "world2", 30 "c": 23, 31 "d": true 32 }, 33 { 34 "a": "hello3", 35 "b": "world3", 36 "c": 24, 37 "d": false 38 } 39 ] 40 var testtow = testmore[1].a 41 alert("第二次"+testtow); 42 43 var testmul = { 44 "name":"css", 45 "sex":"man", 46 "age":22, 47 "hobby": 48 [ 49 { 50 "ball":"basketball", 51 "like":"30%", 52 }, 53 { 54 "ball":"basketball", 55 "like":"70%", 56 }, 57 { 58 "ball":"football", 59 "like":"0%", 60 }, 61 ] 62 } 63 var testthree = testmul.hobby[1].ball+"---"+testmul.hobby[1].like; 64 alert("第三次"+testthree); 65 } 66 </script> 67 <body> 68 hello world 69 </body> 70 </html>
1. { } 對於javascript 讀取對象中的值用 "."
例如第一個例子 var testone = test.c;
2. [ ] 數組中的值 須要添加相對應的鍵值或者索引值
例如第二個例子的 var testtow = testmore[1].a