JSON理解与使用

JSON是什么?

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

语法

JSON的语法可以表示下面三种值:

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

解析与序列化

  1. JSON.stringify()

    此方法用于将JavaScript对象序列化为JSON字符串,可接受三个参数。

    • 第一个参数是要序列化的json数据。
    • 第二个参数可以是一个数组或者函数,起到过滤器的作用。
    • 第三参数为一个数组,表示缩进的空格数,最大缩进数为10,大于10会转化为10

第二个参数为数组

//结果显示返回值与第二个参数数组中的属性对应
    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,"--");
  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属性

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