1、JSON.stringify()
var data = [
{name: "1", sex:1, age: 1},
{name: "2", sex:0, age: 2},
{name: "3", sex:1, age: 3}
];
console.log(JSON.stringify(data));
[{"name":"1","sex":1,"age":1},{"name":"2","sex":0,"age":2},{"name":"3","sex":1,"age":3,"info":{"sex":"male"}}]
- JSON.stringify(value [, replacer])
var data = [
{name: "1", sex:1, age: 1},
{name: "2", sex:0, age: 2},
{name: "3", sex:1, age: 3}
];
console.log( JSON.stringify(data, ["name", "sex"]));
[{"name":"1","sex":1},{"name":"2","sex":0},{"name":"3","sex":1}]
var data = [
{name: "1", sex:1, age: 1},
{name: "2", sex:0, age: 2},
{name: "3", sex:1, age: 3}
];
var str_json = JSON.stringify(data, function (k, v) {
if (k === "sex") {
return ["女", "男"][v];
}
return v;
});
console.log(str_json);
[{"name":"1","sex":"男","age":1},{"name":"2","sex":"女","age":2},{"name":"3","sex":"男","age":3,"info":{}}]
- JSON.stringify(value [, replacer] [, space])
var data = [
{name: "1", sex:1, age: 1},
{name: "2", sex:0, age: 2},
{name: "3", sex:1, age: 3,info:{sex:'male',getSex:function(){return 'sex';}}}
];
var censor = function(key,value){
if(typeof(value) == 'function'){
return Function.prototype.toString.call(value)
}
return value;
}
console.log(JSON.stringify(data,censor,4))
[
{
"name": "1",
"sex": 1,
"age": 1
},
{
"name": "2",
"sex": 0,
"age": 2
},
{
"name": "3",
"sex": 1,
"age": 3,
"info": {
"sex": "male",
"getSex": "function (){return 'sex';}"
}
}
]
2、JSON.parse()
var data = '[{"name":"1","sex":1,"age":1},{"name":"2","sex":0,"age":2},{"name":"3","sex":1,"age":3}]';
JSON.parse(data);
- JSON.parse(text[, reviver])
var data = '[{"name":"1","sex":1,"age":1},{"name":"2","sex":0,"age":2},{"name":"3","sex":1,"age":3}]';
var str_json = JSON.stringify(JSON.parse(data), function (k, v) {
if (k === "sex") {
return ["女", "男"][v];
}
return v;
});
JSON.parse(str_json);
3、jquery操作json
格式:var data = $("#formID").serialize();
功能:将表单内容序列化成一个以&拼接的字符串,键值对的形式,name1=val1&name2=val2&,空格以%20替换。
格式:var jsonData = $("#formID").serializeArray();
功能:将页面表单序列化成一个JSON结构的对象。注意不是JSON字符串。
格式:var string = $("#formID").param();
功能:可以把json格式数据序列化成字符串形式
var obj={a:1,b:2};
$.param(obj);
"a=1&b=2"
格式:var jsonData = $("#formID").serializeJson();
功能:serializeArray()方法的扩展,格式转换为键值对name:val。
$.fn.serializeJson= function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function(){
if(o[this.name]){
if(!o[this.name].push){
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value ||'');
} else {
o[this.name] = this.value || '';
}
});
return o;
};