声名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
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"]
// alert(a[0]["id"])
////添加对象元素
// a[0].school = "清华"
// alert(a[0].school)
JSON字符串与JSON数组之间的相互转换
var str1 = '{ "name": "cxh", "sex": "man" }';
var jsonArr = JSON.parse(str1);
var jsonstr = JSON.stringify(jsonArr);
console.log(jsonArr);
console.log(jsonstr);
-------------------------
[object Object] {
name: "cxh",
sex: "man"
}
"{"name":"cxh","sex":"man"}"
-------------------------