This article mainly introduces the conversion of JSON objects into strings. The article introduces the meaning of parameters, value usage, and space usage. Friends in need can refer to
Serialization
Definition
refers to the process of converting JavaScript values into JSON strings.
JSON.stringify() can convert JavaScript values into JSON strings. The string generated by JSON.stringify() can be restored to a JavaScript value using JSON.parse().
Meaning of parameters
1) JSON.stringify(value[, replacer[, space]])
2) value: required parameter. The JavaScript value being transformed, usually an object or array.
3) replacer: can be omitted. There are two options: function or array.
①- If it is a function, this function will be called for each set of name/value pairs. The function returns a value, which is transformed into the result string as the value of the name. If undefined is returned, the member is neglect.
②- If it is an array, only names that exist in the array can be converted, and the order after conversion is consistent with the values in the array.
4) space: can be omitted. This exists for layout and ease of reading. You can add whitespace or tab characters, etc. to the JSON string.
value usage
Sample code:
<script> var obj = { name : “Geoff Lui”, age : 26 }; console.log(obj); var jsonstr = JSON.stringify(obj); console.log(jsonstr); </script>
Console output execution result:
Usage of replacer
Sample code:
<script> var obj = { name : “Geoff Lui”, age : 26 }; console.log(obj); var jsonstr = JSON.stringify(obj,fun); function fun(name, value){ If (name == “age” ) value = 14; return value; } console.log(jsonstr); </script>
Execution result:
Sample code:
<script> var obj = { a : 1, b : 2, c : 3, d :4 }; console.log(obj); var jsonstr = JSON.stringify(obj,[“a”,”b”,”c”]); console.log(jsonstr); </script>
Execution result:
Usage of space //The arrangement is more readable
Sample code:
<script> var obj = { a : 1, b : 2, c : 3, d :4 }; console.log(obj); var jsonstr = JSON.stringify(obj,[“a”,”b”,”c”], “one”); console.log(jsonstr); </script>
Execution results:
#The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to use JS to detect computer configuration
##Vue.js Flask\ Detailed explanation of building a single-page APP case (with code)
JS summary of traversing irregular multi-dimensional arrays
The above is the detailed content of Convert JSON object to string (detailed code answer attached). For more information, please follow other related articles on the PHP Chinese website!