JSON.stringify 与 JSON.parse 是Javascript自带的吗?


问:
想把object类型数据转换成json格式数据,看到二个函数 JSON.stringify() 和 JSON.parse()。 在firefox、chrome、IE8上面测试,都可以执行。但是这两个是Javascript自带的吗?还是各浏览器自己支持的?
答:
早期的JSON解析器基本上就是使用JavaScript的eval()函数。由于JSON是JavaScript语法的自己,因此eval()函数可以解析、解释并返回JavaScript的对象和数组。
ECMAScript 5对解析JSON的行为进行了规范,定义了全局对象JSON。
JSON对象有两个方法:stringify()和parse()。
在最简单的情况下,这两个方法分别用于把JavaScript对象序列化为JSON字符串和把JSON字符串解析为原生JavaScript。
看这里:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object
described by the string. An optional reviver function can be provided to perform a
transformation on the resulting object before it is returned.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

The JSON.stringify() method converts a JavaScript object or value to a JSON string,
optionally replacing values if a replacer function is specified or optionally including only the
specified properties if a replacer array is specified.
console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"
console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// expected output: "[3,"false",false]"
console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// expected output: "{"x":[10,null,null,null]}"
console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// expected output: ""2006-01-02T15:04:05.000Z""