JSON有陣列(Array)跟物件(Object)兩者
- 陣列(Array)用:[]
- 物件(Object)用:{}
- 一個Name可以對應一個Value
目前我有一個JSON格式為:
{ "Kaohsiung" : [ { "zip" : 800, "city" : "新興區" },{ "zip" : 801, "city" : "前金區" },{ "zip" : 802, "city" : "苓雅區" },{ "zip" : 803, "city" : "鹽埕區" },{ "zip" : 804, "city" : "鼓山區" },{ "zip" : 805, "city" : "旗津區" },{ "zip" : 806, "city" : "前鎮區" },{ "zip" : 807, "city" : "三民區" },{ "zip" : 811, "city" : "楠梓區" },{ "zip" : 812, "city" : "小港區" },{ "zip" : 813, "city" : "左營區" },{ "zip" : 814, "city" : "仁武區" },{ "zip" : 815, "city" : "大社區" },{ "zip" : 820, "city" : "岡山區" },{ "zip" : 821, "city" : "路竹區" },{ "zip" : 822, "city" : "阿蓮區" },{ "zip" : 823, "city" : "田寮區" },{ "zip" : 824, "city" : "燕巢區" },{ "zip" : 825, "city" : "橋頭區" },{ "zip" : 826, "city" : "梓官區" },{ "zip" : 827, "city" : "彌陀區" },{ "zip" : 828, "city" : "永安區" },{ "zip" : 829, "city" : "湖內區" },{ "zip" : 830, "city" : "鳳山區" },{ "zip" : 831, "city" : "大寮區" },{ "zip" : 832, "city" : "林園區" },{ "zip" : 833, "city" : "鳥松區" },{ "zip" : 840, "city" : "大樹區" },{ "zip" : 842, "city" : "旗山區" },{ "zip" : 843, "city" : "美濃區" },{ "zip" : 844, "city" : "六龜區" },{ "zip" : 845, "city" : "內門區" },{ "zip" : 846, "city" : "杉林區" },{ "zip" : 847, "city" : "甲仙區" },{ "zip" : 848, "city" : "桃源區" },{ "zip" : 849, "city" : "三民區" },{ "zip" : 851, "city" : "茂林區" },{ "zip" : 852, "city" : "茄萣區" } ] }
我希望可以在Console輸出新興區,利用j去呼叫Kaohsiung陣列的第0個值,並取得他的zip以及city只要在js加入以下程式碼就行了
console.debug(j.Kaohsiung[0].zip); console.debug(j.Kaohsiung[0].city);
成果如下:
完整程式碼:
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>test</title> <script type="text/javascript"> var j = { "Kaohsiung" : [ { "zip" : 800, "city" : "新興區" },{ "zip" : 801, "city" : "前金區" },{ "zip" : 802, "city" : "苓雅區" },{ "zip" : 803, "city" : "鹽埕區" },{ "zip" : 804, "city" : "鼓山區" },{ "zip" : 805, "city" : "旗津區" },{ "zip" : 806, "city" : "前鎮區" },{ "zip" : 807, "city" : "三民區" },{ "zip" : 811, "city" : "楠梓區" },{ "zip" : 812, "city" : "小港區" },{ "zip" : 813, "city" : "左營區" },{ "zip" : 814, "city" : "仁武區" },{ "zip" : 815, "city" : "大社區" },{ "zip" : 820, "city" : "岡山區" },{ "zip" : 821, "city" : "路竹區" },{ "zip" : 822, "city" : "阿蓮區" },{ "zip" : 823, "city" : "田寮區" },{ "zip" : 824, "city" : "燕巢區" },{ "zip" : 825, "city" : "橋頭區" },{ "zip" : 826, "city" : "梓官區" },{ "zip" : 827, "city" : "彌陀區" },{ "zip" : 828, "city" : "永安區" },{ "zip" : 829, "city" : "湖內區" },{ "zip" : 830, "city" : "鳳山區" },{ "zip" : 831, "city" : "大寮區" },{ "zip" : 832, "city" : "林園區" },{ "zip" : 833, "city" : "鳥松區" },{ "zip" : 840, "city" : "大樹區" },{ "zip" : 842, "city" : "旗山區" },{ "zip" : 843, "city" : "美濃區" },{ "zip" : 844, "city" : "六龜區" },{ "zip" : 845, "city" : "內門區" },{ "zip" : 846, "city" : "杉林區" },{ "zip" : 847, "city" : "甲仙區" },{ "zip" : 848, "city" : "桃源區" },{ "zip" : 849, "city" : "三民區" },{ "zip" : 851, "city" : "茂林區" },{ "zip" : 852, "city" : "茄萣區" } ] }; console.debug(j.Kaohsiung[0].zip); console.debug(j.Kaohsiung[0].city); </script> </head> <body> </body> </html>
參考資料:
http://www.json.org/