JSON(JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。JSON是JavaScript原生格式,这意味着在JavaScript中处理JSON数据不需要任何特殊的API或工具包。
JSON的规则很简单:对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’对”之间使用“,”(逗号)分隔。
规则如下:
1)映射用冒号(“:”)表示。名称:值
2)并列的数据之间用逗号(“,”)分隔。名称1:值1,名称2:值2
3) 映射的集合(对象)用大括号(“{}”)表示。{名称1:值1,名称2:值2}
4) 并列数据的集合(数组)用方括号(“[]”)表示。
[
{名称1:值,名称2:值2},
{名称1:值,名称2:值2}
]
5) 元素值可具有的类型:string, number, object, array, true, false, null
JSON 用冒号(而不是等号)来赋值。每一条赋值语句用逗号分开。整个对象用大括号封装起来。可用大括号分级嵌套数据。
对象描述中存储的数据可以是字符串,数字或者布尔值。对象描述也可存储函数,那就是对象的方法。
例子一:
<script language="JavaScript"> var people ={"firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" }; alert(people.firstName); alert(people.lastName); alert(people.email); </script>
例子二:
<script language="JavaScript"> var people =[ {"firstName": "Brett","email": "[email protected]" }, {"firstName": "Mary","email": "[email protected]" } ]; alert(people[0].firstName); alert(people[0].email); alert(people[1].firstName); alert(people[1].email); </script>
例子三:
<script language="JavaScript"> var people ={ "programmers": [ {"firstName": "Brett", "email": "[email protected]" }, {"firstName": "Jason", "email": "[email protected]" } ] }; window.alert(people.programmers[0].firstName); window.alert(people.programmers[1].email); </script>
例子四:
<script language="JavaScript"> var people ={ "programmers": [ { "firstName": "Brett", "email": "[email protected]" }, { "firstName": "Jason", "email": "[email protected]" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" } ], "authors": [ { "firstName": "Isaac", "genre": "science fiction" }, { "firstName": "Tad", "genre": "fantasy" }, { "firstName": "Frank", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "instrument": "guitar" }, { "firstName": "Sergei", "instrument": "piano" } ]}; window.alert(people.programmers[1].firstName); window.alert(people.musicians[1].instrument); </script>
例子五:
<script language="JavaScript"> var people ={ "username":"mary", "age":"20", "info":{"tel":"1234566","celltelphone":788666}, "address":[ {"city":"beijing","code":"1000022"}, {"city":"shanghai","code":"2210444"} ] }; window.alert(people.username); window.alert(people.info.tel); window.alert(people.address[0].city); </script>