JSON学习

声名json数组:
var a = [{
    "id": "1",
    "name": "zhangsan",
    "age": "10"
}, {
    "id": "2",
    "name": "lisi",
    "age": "20"
}, {
    "id": "3",
    "name": "wangwu",
    "age": "30"
}];
json转string: JSON.stringify(a)
string转json:eval(JSON.stringify(a))
添加json对象:
var obj = {"id":"4","name":"zhaoliu","age":"40"};
a.push(obj);
删除json对象:delete a[0];//删除数组a当中的第一个对象,但数组长度不会减1;
添加json元素:
修改json元素值:
a[0]["id"] = "2”;//或a[0].id = “2”;
alert(a[0]["id"]);//2
删除json元素:
delete a[0]["id"];//删除数组a当中第一个对象的id元素,key,value同时删除
alert(a[0]["id"]);//undefined
格式化json工具:http://tool.oschina.net/codeformat/json
测试环境说明:使用jsBin测试工具进行测试,http://jsbin.com/?js,output
var a = [{
    "id": "1",
    "name": "zhangsan",
    "age": "10"
}, {
    "id": "2",
    "name": "lisi",
    "age": "20"
}, {
    "id": "3",
    "name": "wangwu",
    "age": "30"
}];

//json数组转string
alert(JSON.stringify(a));

//string 转json数组
alert(eval(JSON.stringify(a)));

////新增一个对象,数组长度+1
// var obj = {"id":"4","name":"zhaoliu","age":"40"};
// a.push(obj);
// alert(a.length);
////删除固定的对象,数组长度不变
// delete a[4];
// alert(a.length +"********"+ a[4]);

////删除对象元素
// delete a[0]["id"];//或delete a[0].id;
// alert(a[0]["id"]);

////添加对象元素
// a[0].school = "清华";
// alert(a[0].school);
JSON字符串与JSON数组之间的相互转换
var str1 = '{ "name": "cxh", "sex": "man" }';
var jsonArr = JSON.parse(str1);//转换为json数组
var jsonstr = JSON.stringify(jsonArr);//转换为json字符串

console.log(jsonArr);
console.log(jsonstr);

-------------------------
[object Object] {
  name: "cxh",
  sex: "man"
}
"{\"name\":\"cxh\",\"sex\":\"man\"}"

-------------------------
posted @ 2015-06-30 18:14  peng_gy  阅读(106)  评论(0编辑  收藏  举报