Json技术使用代码示例
json格式细节1
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格式细节2
JSON 用冒号(而不是等号)来赋值。每一条赋值语句用逗号分开。整个对象用大括号封装起来。可用大括号分级嵌套数据。
对象描述中存储的数据可以是字符串,数字或者布尔值。对象描述也可存储函数,那就是对象的方法。
json格式其它解析案例
例子一:
var people ={"firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }; alert(people.firstName); alert(people.lastName); alert(people.email);
例子二:
var people =[ {"firstName": "Brett","email": "brett@newInstance.com" }, {"firstName": "Mary","email": "mary@newInstance.com" } ]; alert(people[0].firstName); alert(people[0].email); alert(people[1].firstName); alert(people[1].email);
例子三:
var people ={ "programmers": [ {"firstName": "Brett", "email": "brett@newInstance.com" }, {"firstName": "Jason", "email": "jason@servlets.com" } ] }; window.alert(people.programmers[0].firstName); window.alert(people.programmers[1].email);
例子四:
var people ={ "programmers": [ { "firstName": "Brett", "email": "brett@newInstance.com" }, { "firstName": "Jason", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "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);
例子五:
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);