标签:javascript json
JSON的规则很简单:对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’对”之间使用“,”(逗号)分隔。具体细节参考http://www.json.org/json-zh.html
一直以来解析JSON都是使用的org.json包,进行的后台解析,
http://blog.csdn.net/gaopeng0071/article/details/25873407
现在这里转载下前台的解析方式。
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来简单的修改数据,修改上面的例子
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数据。
更多用法参考:http://www.jb51.net/article/21452.htm
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());
}
JavaScript -- 使用JavaScript解析JSON格式的字符串
标签:javascript json
原文地址:http://blog.csdn.net/gaopeng0071/article/details/46442107