JSON理解与使用

JSON是什么?

json是一种数据结构,并不丛属于Js。json

语法

JSON的语法能够表示下面三种值:数组

  • 简单值:字符串,数组,布尔值和null。
//json的字符串必须使用双引号
'hello'
  • 对象
//注意:
//1.末尾不要有分号
//2.对象的属性值必定要加双引号
{
    "name":"Mary",
    "age":21
}
  • 数组
['Mary','Lily','Jim']
  • JSON不支持变量,函数和对象实例。数据结构

    解析与序列化

  1. JSON.stringify()函数

    此方法用于将JavaScript对象序列化为JSON字符串,可接受三个参数。
    • 第一个参数是要序列化的json数据。
    • 第二个参数能够是一个数组或者函数,起到过滤器的做用。
    • 第三参数为一个数组,表示缩进的空格数,最大缩进数为10,大于10会转化为10

第二个参数为数组this

//结果显示返回值与第二个参数数组中的属性对应
    var student={
    "name":"Mary",
    "age":22,
    "course":["English","Math"],
    "class":1
}
var test1=JSON.stringify(student,["age","name"]);

结果显示返回值与第二个参数数组中的属性对应code

第二个参数为数组对象

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;
    }
});

结果:blog

//缩进4个空格
var test3=JSON.stringify(student,null,4);
//将缩进换成制表符
var test3=JSON.stringify(student,null,"--");
  1. toJSONf()
    能够为任何添加toJSON()方法,能够让toJSON()方法返回任何序列化的值,也能够返回undefined,若是toJSON()嵌套在另外一个对象中,会返回null.
var studentTwo={
    "name":"Mary",
    "age":22,
    "course":["English","Math"],
    "class":1,
    toJSON:function(){
        return this.name;
    }
}
var test3=JSON.stringify(studentTwo);

只显示了name属性ip

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 (中国标准时间)

相关文章
相关标签/搜索