在开发的过程中,对json的接触基本是前端页面搭建完成后,对后台数据的请求。如果接口尚未提供,一般情况下会先按规定的要求写好需要的json模拟出请求的后台数据。json的格式有很多种,关注的主体是data里面的内容。
$(function(){
//转换为字符串1
var data = [
{name: "王尼玛", sex:1, age: 30},
{name: "王尼美", sex:0, age: 20},
{name: "王大锤", sex:1, age: 30},
{name: "23", sex:1, age: 30}
];
var str_json = JSON.stringify(data, function (k, v) {
if (k === "sex") {
return ["女", "男"][v];
}
return v;
});
console.log(str_json);
// [{"name":"王尼玛","sex":"男","age":30},{"name":"王尼美","sex":"女","age":20},{"name":"王大锤","sex":"男","age":30},{"name":"23","sex":"男","age":30}]
//转换为字符串2
var data = [
{name: "王尼玛", sex:1, age: 30},
{name: "王尼美", sex:0, age: 20},
{name: "王大锤", sex:1, age: 30}
];
var str_json = JSON.stringify(data, ["name", "sex"]);
console.log(str_json);
// [{"name":"王尼玛","sex":1},{"name":"王尼美","sex":0},{"name":"王大锤","sex":1}]
})
不常用,但是需要记住的这几种用法。