php生成json格式
使用頁面
代碼如下:
<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());
}