两者对比
对比 | .stringify() | .parse() |
---|---|---|
定义 | json对象->字符串 | 字符串->json对象 |
语法 | JSON.stringify(value [, replacer] [, space]) | JSON.parse(text[, reviver]) |
对象转化为字符串输出
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"}}]
输出部分数据
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}]
sex0,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;
});//sex 0,1->女,男
console.log(str_json);
[{"name":"1","sex":"男","age":1},{"name":"2","sex":"女","age":2},{"name":"3","sex":"男","age":3,"info":{}}]
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';}"
}
}
]
var data = '[{"name":"1","sex":1,"age":1},{"name":"2","sex":0,"age":2},{"name":"3","sex":1,"age":3}]';
JSON.parse(data);
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;
});//sex 0,1->女,男
JSON.parse(str_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;
};