本文实例讲述了javascript解析json的方法。分享给大家供大家参考。具体方法如下:
下载json库
http://www.json.org/json-zh.html自己找javascript的
或者直接去下面的
https://github.com/douglascrockford/JSON-js
php生成json格式
使用页面
复制代码 代码如下:
<script src="scripts/json.js"></script>
alert(data.toJSONString());
alert(data.toJSONString());
如果返回false说明没数据
js 代码:
复制代码 代码如下:
functionshowJSON() {
varuser =
{
"username":"tom",
"age":20,
"info": {"tel":"123456","cellphone":"98765"},
"address":
[
{"city":"shanghai","postcode":"201203"},
{"city":"suzhou","postcode":"200000"}
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
}
varuser =
{
"username":"tom",
"age":20,
"info": {"tel":"123456","cellphone":"98765"},
"address":
[
{"city":"shanghai","postcode":"201203"},
{"city":"suzhou","postcode":"200000"}
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
}
修改
复制代码 代码如下:
user.username ="jerry";
可以使用eval来转换JSON字符到Object
复制代码 代码如下:
functionmyEval() {
varstr = '{"name":"Violet","occupation":"character"}';
varbj = eval('(' + str + ')');
alert(obj.toJSONString());
}
varstr = '{"name":"Violet","occupation":"character"}';
varbj = eval('(' + str + ')');
alert(obj.toJSONString());
}
或者使用parseJSON()方法
复制代码 代码如下:
functionmyEval() {
varstr = '{"name":"Violet","occupation":"character"}';
varbj = str.parseJSON();
alert(obj.toJSONString());
}
varstr = '{"name":"Violet","occupation":"character"}';
varbj = str.parseJSON();
alert(obj.toJSONString());
}
希望本文所述对大家的javascript程序设计有所帮助。