The two methods of JSON objects: JSON.parse() and JSON.stringify() are usually used to convert between JSON objects and strings. They will not be described in detail here. You can check this article: http://www.css88.com/archives/3919 .
Let me introduce here. I mainly introduce the advanced usage of JSON.parse() and JSON.stringify(), which can bring us some convenience in practical applications.
JSON.parse()
JSON.parse() can accept a second parameter, which can convert the object value before returning it. For example, in this example, capitalize the property values of the returned object:
JavaScript code:
const user = { name: 'John', email: 'john@awesome.com', plan: 'Pro' }; const userStr = JSON.stringify(user); const newUserStr = JSON.parse(userStr, (key, value) => { if (typeof value === 'string') { return value.toUpperCase(); } return value; }); console.log(newUserStr); //{name: "JOHN", email: "JOHN@AWESOME.COM", plan: "PRO"}
Note: Trailing commas are not valid in JSON, so JSON.parse() will throw an error if the string passed to it has trailing commas.
JSON.stringify()
JSON.stringify() can take two additional parameters, the first is a replacement function, and the second is an interval string, which is used to separate the returned string.
parameter:
value : The javascript object that will be converted to JSON string.
Replcer: This parameter can be of many types. If it is a function, it can change the behavior of a javascript object during strings. If it is an array containing String and Number objects, it will be a whitelist. Only those key-value pairs whose keys exist in the whitelist will be included in the final generated JSON string. If the parameter value is null or omitted, all key-value pairs will be included in the final generated JSON in the string.
Space: This parameter can be a String or Number object, which is used to insert white space characters into the output JSON string to enhance readability. If it is a Number object, it indicates how many spaces to use as blanks; Maximum can be 10, values greater than 10 can also be 10. Minimum can be 1. Values less than 1 are invalid and no white space character is displayed. If it is a String object, the string itself acts as a blank character and can be up to 10 characters long. The first ten characters are truncated if exceeded. If the parameter is omitted (or null), no white space character is displayed
Replacement functions can be used to filter values, since any value that returns undefined will not be in the returned string:
JavaScript code:
const user = { id: 229, name: 'John', email: 'john@awesome.com' }; function replacer(key, value) { console.log(typeof value); if (key === 'email') { return undefined; } return value; } const userStr = JSON.stringify(user, replacer); // "{"id":229,"name":"John"}"
Example of passing in an interval parameter:
JavaScript code:
const user = { name: 'John', email: 'john@awesome.com', plan: 'Pro' }; const userStr = JSON.stringify(user, null, '...'); // "{ // ..."name": "John", // ..."email": "john@awesome.com", // ..."plan": "Pro" // }"
toJSON method
If a serialized object has a toJSON method, then the toJSON method will override the default serialization behavior of the object: not the object is serialized, but the return value of the toJSON method will be serialized
JavaScript code:
var obj = { foo: 'foo', toJSON:function(){ return 'bar'; } } JSON.stringify(obj);//'"bar"' JSON.stringify({x:obj});//'{"x":"bar"}'
Using the toJSON method, we can modify the default behavior of converting objects to JSON.
Formatting objects with JSON.stringify
In actual use, we may format some complex objects, which are often nested objects within objects. It doesn't seem so intuitive directly, combined with the replacer and space parameters above, we can format complex objects like this:
JavaScript code:
var censor = function(key,value){ if(typeof(value) == 'function'){ return Function.prototype.toString.call(value) } return value; } var foo = {bar:"1",baz:3,o:{name:'xiaoli',age:21,info:{sex:'male',getSex:function(){return 'sex';}}}}; console.log(JSON.stringify(foo,censor,4))
The actual returned string, remember that it is a string, as follows:
JavaScript code:
{ "bar": "1", "baz": 3, "o": { "name": "xiaoli", "age": 21, "info": { "sex": "male", "getSex": "function (){return 'sex';}" } } }
end! !