1. 什么是JSON。JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。 JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要任何特殊的 API 或工具包。
{ "people": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" }
]}
语义说明(个人总结,不完全正确):
1。对象用{}表示,
2。键值对之间用 : 割开,键或值用双引号引起来。
3。数组用[]表示
4。 多个键值对之间用逗号 ,分开。
以下代码绝大多数来自于: 主题:JSON学习: http://www.iteye.com/topic/71343, 放到这里只是为了总结,如有侵犯原作版权,请联系本博主。[本文以下部分版权归原作所有]
js 读取 json
function showJSON() { var user = { "username":"andy", "age":20, "info": { "tel": "123456", "cellphone": "98765"}, "address": [ {"city":"beijing","postcode":"222333"}, {"city":"newyork","postcode":"555666"} ] } alert(user.username); alert(user.age); alert(user.info.cellphone); alert(user.address[0].city); alert(user.address[0].postcode); }
2。 js 修改 JSON
function showJSON() { var user = { "username":"andy", "age":20, "info": { "tel": "123456", "cellphone": "98765"}, "address": [ {"city":"beijing","postcode":"222333"}, {"city":"newyork","postcode":"555666"} ] } alert(user.username); alert(user.age); alert(user.info.cellphone); alert(user.address[0].city); alert(user.address[0].postcode); user.username = "Tom"; alert(user.username); }
JSON提供了json.js包,下载http://www.json.org/json.js 后,将其引入然后就可以简单的使用object.toJSONString()转换成JSON数据。
function showCar() { var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); alert(carr.toJSONString()); } function Car(make, model, year, color) { this.make = make; this.model = model; this.year = year; this.color = color; }
可以使用eval来转换JSON字符到Object
function myEval() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = eval('(' + str + ')'); alert(obj.toJSONString()); }
或者使用parseJSON()方法
function myEval() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = str.parseJSON(); alert(obj.toJSONString()); }
js 中数组引用
var people =
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" }
],
"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" }
]
}
people.programmers[0].lastName;
参考:
http://www.iteye.com/topic/71343
掌握 Ajax,第 10 部分: 使用 JSON 进行数据传输(IBM)