javascript解析json
下载json库
http://www.json.org/json-zh.html自己找javascript的
或者直接去下面的
https://github.com/douglascrockford/JSON-js
php生成json格式
使用页面
[html] view plaincopyprint?
<script src="scripts/json.js"></script>
alert(data.toJSONString());
[html] view plaincopyprint?
<script src="scripts/json.js"></script>
alert(data.toJSONString());
<script src="scripts/json.js"></script>
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);
}
修改
user.username ="jerry";
可以使用eval来转换JSON字符到Object
functionmyEval() {
varstr = '{"name":"Violet","occupation":"character"}';
varbj = eval('(' + str + ')');
alert(obj.toJSONString());
}
或者使用parseJSON()方法
functionmyEval() {
varstr = '{"name":"Violet","occupation":"character"}';
varbj = str.parseJSON();
alert(obj.toJSONString());
}
摘自 刘海闯的专栏