JSON对象包含两个方法,一个是把js对象转换成json字符串,另一个是把对象转化成json类型的数据。
分别为JSON.stringify() 和JSON.parse()
The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can’t be called or constructed, and aside from its two method properties it has no interesting functionality of its own.
1.
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.
Syntax
JSON.parse(text[, reviver])
Parameters
text
The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver Optional
If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Return value
The Object corresponding to the given JSON text.
Exceptions
Throws a SyntaxError exception if the string to parse is not valid JSON.
Examples
Using JSON.parse()
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
Using the reviver parameter
If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver, which is called with the object containing the property being processed as this and with the property name as a string and the property value as arguments. If the reviver function returns undefined (or returns no value, e.g. if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value.
If the reviver only transforms some values and no others, be certain to return all untransformed values as-is, otherwise they will be deleted from the resulting object.
JSON.parse('{"p": 5}', (key, value) =>
typeof value === 'number'
? value * 2 // return value * 2 for numbers
: value // return everything else unchanged
);
// { p: 10 }
JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
console.log(key); // log the current property name, the last is "".
return value; // return the unchanged property value.
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""
JSON.parse() does not allow trailing commas
(parse不允许尾随一个逗号)
// both will throw a SyntaxError
JSON.parse(‘[1, 2, 3, 4, ]’);
JSON.parse(‘{“foo” : 1, }’);
2.
The JSON.stringify() method converts a JavaScript 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.
Syntax
JSON.stringify(value[, replacer[, space]])
Parameters
value
The value to convert to a JSON string.
replacer Optional
A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
space Optional
A String or Number object that’s used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 if it’s larger than that. Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it’s longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.
Return value
A JSON string representing the given value.
Description
JSON.stringify() converts a value to JSON notation representing it:
Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in “pure” values like JSON.stringify(function(){}) or JSON.stringify(undefined).
All symbol-keyed properties will be completely ignored, even when using the replacer function.
Non-enumerable properties will be ignored
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify('foo'); // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'
JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
// '"2006-01-02T15:04:05.000Z"'
JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
// '[1,"false",false]'
JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] });
// '{"x":[10,null,null,null]}'
// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
// '{}'
JSON.stringify({ [Symbol('foo')]: 'foo' });
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
if (typeof k === 'symbol') {
return 'a symbol';
}
});
// '{}'
// Non-enumerable properties:
JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
// '{"y":"y"}'
The replacer parameter
The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer’s this parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string, as follows:
If you return a Number, the string corresponding to that number is used as the value for the property when added to the JSON string.
If you return a String, that string is used as the property’s value when adding it to the JSON string.
If you return a Boolean, “true” or “false” is used as the property’s value, as appropriate, when adding it to the JSON string.
If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.
If you return undefined, the property is not included (i.e., filtered out) in the output JSON string.
Note: You cannot use the replacer function to remove values from an array. If you return undefined or a function then null is used instead.
(不能用replacer函数去移除数组里的某些值,否则就会返回一个未定义或者空值)