var guagua = { name: '小明', age: 14, gender: true, height: 1.65, grade: null, 'middle-school': '\"W3C\" Middle School', skills: ['JavaScript', 'Java', 'Python', 'Lisp'] }; JSON.stringify(xiaoming); // '{"name":"小明","age":14,"gender":true,"height":1.65,"grade":null," middle-school":"\"W3C\" Middle School","skills": ["JavaScript","Java","Python","Lisp"]}'
结果:
{ "name": "小明", "age": 14, "gender": true, "height": 1.65, "grade": null, "middle-school": "\"W3C\" Middle School", "skills": [ "JavaScript", "Java", "Python", "Lisp" ] }
第二个参数用于控制如何筛选对象的键值,如果我们只想输出指定的属性,可以传入Array:
JSON.stringify(xiaoming, ['name', 'skills'], ' ');
结果:
{ "name": "guagua", "skills": [ "JavaScript", "Java", "Python", "Lisp" ] }
还可以传入一个函数,这样对象的每个键值对都会被函数先处理:
function convert(key, value) { if (typeof value === 'string') { return value.toUpperCase(); } return value; } JSON.stringify(guagua, convert, ' ');
上面的代码把所有属性值都变成大写:
{ "name": "guagua", "age": 14, "gender": true, "height": 1.65, "grade": null, "middle-school": "\"W3C\" MIDDLE SCHOOL", "skills": [ "JAVASCRIPT", "JAVA", "PYTHON", "LISP" ] }
如果我们还想要精确控制如何序列化小明,可以给xiaoming定义一个toJSON()的方法,直接返回JSON应该序列化的数据:
反序列化
拿到一个JSON格式的字符串,我们直接用JSON.parse() 把它变成一个JavaScript 对象:
JSON.parse('[1,2,3,true]'); //[1,2,3,true] JSON.parse('{"name":"瓜瓜","age":14}'); // Object{name:'瓜瓜',age:14} JSON.parse('true'); // true JSON.parse('123.45'):// 123.45 JSON.parse()还可以接收一个函数,用来转换解析出的属性: JSON.parse('{"name":"guagua","age":14}',function(key,value){ //把number * 2 if(key ==='name'){ return value + '同学' } return value; }) ; // Object{name: '瓜瓜同学',age: 14}
以上这篇浅析JavaScript 箭头函数 generator Date JSON就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章: