JSON官方网站:http://json.org
JSON(JavaScript Object Notation):是一种轻量级的数据交换语言,易于人阅读和编写,同时也易于机器解析和生成(如果还是不理解,就把它当成和XML差不多)。
JSON的书写结构:
1) “名称/值”对的集合(A collection of name/value pairs)
不同的语言中,它被理解为对象(object)、记录(record)、结构(struct)、字典(dictionary)、
哈希表(hash table)、有键列表(keyed list)、或者关联数组。
2) 值的有序列表(An ordered list of values)。
在大部分语言中,它被理解为数组(array)。
1.表示 名/值 对:
{“firstName”:"Tom"}或 {"firstName":"Tom", "lastName":"temp", "tel":"123455"}
多个值对之间用逗号隔开。
2. 表示数组:
{“peopel”:[
{"firstName":"a", "lastName":"aa", "tel":"aaa"},
{"firstName":"b", "lastName":"bb", "tel":"ccc"},
{"firstName":"c", "lastName":"cc", "tel":"ccc"},
]
}
上边这段JSON数据的意思为:有一个pelple数组, 里面有三个人的firstName、lastName、tel信息。
看一个更多数据的:
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}
在javascript中定义一个json变量:
<script type="text/javascript">
var jsonData = {"firstName" : "Tom"};
</script>
访问JSON数据:访问JSON数据主要使用 点( . ) 和 下标([ 1 ]) 来访问。
看如下一段json数据
var people = { "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }
获取authors整个数组:people.authors
获取authors数组里面第二个数据的lastName::people.authors[1].lastName , 获取到的结果就是: Williams
修改JSON数据:
1)或取到要修改的JSON数据
2)用等号( = )相连 , 并在右侧赋予新值。
例如要修改上面获取的值: people.authors[1].lastName = "Jomson" 即:将原来的Williams 改成 Jomson.