在数据传输过程中,json是以文本,即字符串的形式传递的,而JS操作的是JSON对象,所以,JSON对象和JSON字符串之间的相互转换是关键。例如:
//JSON字符串: var str1 = '{ "name": "cxh", "sex": "man" }'; //JSON对象: var str2 = { "name": "cxh", "sex": "man" }; //JSON字符串 -> JSON对象 var obj = JSON.parse(str1); //JSON对象 -> JSON字符串 var obj2 = JSON.stringify(str2); console.log(obj); console.log(obj2);
JSON.stringify扩展
var data =[ { name: "刘德华",sex:"1",age:26 }, { name: "张学友",sex:"0",age:20 }, { name: "黎明",sex:"1",age:22 }, { name: "郭富城",sex:"1",age:18 } ]; //输出选择字段 console.log(JSON.stringify(data,["name","sex"])); //回调函数做一个映射关系 var str_json = JSON.stringify(data,function(key,value){ if(key == 'sex'){ return ["女",'男'][value]; } return value; }); console.log(str_json); //格式化字符串 console.log(JSON.stringify(data,["name","sex"]," "));