JSON.parse()和JSON.stringify()

2021-03-22  本文已影响0人  phoebe__liu

JSON.parse()方法将数据转换为 JavaScript 对象。

var str = '{"name":"jianshu","age":"18"}'
JSON.parse(str)
//{name: "huangxiaojian", age: "23"}

JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串,如果指定了一个 replacer 函数,则可以选择性地替换值,或者指定的 replacer 是数组,则可选择性地仅包含数组指定的属性。

console.log(JSON.stringify({ x: 1, y: 2 }));
//"{"x":1,"y":2}"

console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
//  "[3,"false",false]"

console.log(JSON.stringify({ x: [4, undefined, function(){}, Symbol('')] }));
// "{"x":[4,null,null,null]}"

console.log(JSON.stringify(new Date(2021, 2, 22, 18, 4, 5)));
//  "2021-03-22T10:04:05.000Z"
上一篇 下一篇

猜你喜欢

热点阅读