JSON的规则很简单: 对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。具体细节参考http://www.json.org/json-zh.html
举个简单的例子:
js 代码
- 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, age, info, address 等属性。
同样也可以用JSON来简单的修改数据,修改上面的例子
js 代码
- 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数据。
js 代码
- 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
js 代码
- function myEval() {
- var str = '{ "name": "Violet", "occupation": "character" }';
- var obj = eval('(' + str + ')');
- alert(obj.toJSONString());
- }
或者使用parseJSON()方法
js 代码
- function myEval() {
- var str = '{ "name": "Violet", "occupation": "character" }';
- var obj = str.parseJSON();
- alert(obj.toJSONString());
- }