json是一种数据结构,并不丛属于Js。
JSON的语法可以表示下面三种值:
//json的字符串必须使用双引号
'hello'//注意:
//1.末尾不要有分号
//2.对象的属性值一定要加双引号
{
    "name":"Mary",
    "age":21
}['Mary','Lily','Jim']JSON不支持变量,函数和对象实例。
JSON.stringify()
此方法用于将JavaScript对象序列化为JSON字符串,可接受三个参数。第二个参数为数组
//结果显示返回值与第二个参数数组中的属性对应
    var student={
    "name":"Mary",
    "age":22,
    "course":["English","Math"],
    "class":1
}
var test1=JSON.stringify(student,["age","name"]);结果显示返回值与第二个参数数组中的属性对应

第二个参数为数组
var student={
    "name":"Mary",
    "age":22,
    "course":["English","Math"],
    "class":1
}
//返回undefined表示删除该属性
//可以返回自定义后的值
var test2=JSON.stringify(student,function(key,value){
    switch(key){
        case "name":
        return undefined;
        case "age":
        return value+1;
        case "class":
        return 2;
        default:
        return value;
    }
});结果:

//缩进4个空格
var test3=JSON.stringify(student,null,4);
//将缩进换成制表符
var test3=JSON.stringify(student,null,"--");var studentTwo={
    "name":"Mary",
    "age":22,
    "course":["English","Math"],
    "class":1,
    toJSON:function(){
        return this.name;
    }
}
var test3=JSON.stringify(studentTwo);只显示了name属性

toJSON()可以做过滤器的补充,但是需要理解序列化的内部顺序

JSON.parse()方法
将JSON字符串解析为原生的JavaScript值。
//data是一个JSON字符串
var test4=JSON.parse(data);JSON.stringify还可以接收另一个参数,该参数为一个函数,与JSON.stringify的过滤相比,这个函数的作用是还原。
var studentThree={
    "name":"Mary",
    "age":22,
    "course":["English","Math"],
    "date":new Date(2019,9,10),
    "class":1
}
var test5=JSON.stringify(studentThree);
alert(test5);结果json字符串

var test6=JSON.parse(test5);
alert(test6.date);结果为2019-10-09T16:00:00.000Z
//如果还原函数返回undefined,表示要删除该函数,如果返回其他值,表示将该值插入到结果中
var test7=JSON.parse(test5,function(key,value){
    if(key==="date"){
        return new Date(value);
    }else{
        return value;
    }
});
alert(test7);结果为一个对象
alert(test7.date);结果:Thu Oct 10 2019 00:00:00 GMT+0800 (中国标准时间)
原文:https://www.cnblogs.com/ellen-mylife/p/11452153.html