Overview
JSON.stringify()method to serialize any JavaScript value into a JSON string.
Grammar
JSON.stringify(valuereplacerspace]])
Parameters
-
value
-
The value that will be serialized into a JSON string.
-
replacer options available
-
If the parameter is a function, each property of the serialized value is transformed and processed by the function during serialization, and if the parameter is an array, only the name of the property contained in the array is serialized into the final JSON string. For more detailed explanations and examples of this parameter, refer to the article using native JSON objects.
-
space options available
-
specifies a blank string for indentation, which is used to beautify the output (pretty-print).
Refer to Mdn:https://developer.mozilla.org/zh-cn/docs/web/javascript/reference/global_objects/json/stringify for details
In general, we use only the following code for a simple JSON string:
var Jsonobj = {"Name": "Value", "arr": [' str1 ', ' str2 ']};console.log (json.stringify (jsonobj)); //Result {"name": "Value", "arr": ["str1", "str2"]}
Two, in fact, the second parameter also has a very important purpose, for example, the Key-value in the object is processed and then converted to a string:
var Jsonobj = {"Name": "Value", "name2": "value2", "arr": [' str1 ', ' str2 ', {' arrobj ': ' Arrobj '}]}; Json.stringify (jsonobj,function(key,value) { console.log (key,value)}); // The result is: Jsonobj object (value), key no value
Third, when the JSON strings that need to be displayed are user-friendly and increase readability, you can use the three parameters:
var Jsonobj = {"Name": "Value", "arr": [' str1 ', ' str2 ', {' arrobj ': ' arrobj 'null, ' \ t '); /* "{ " "name": "Value", "arr": [ "str1", "str2", { "arrobj": "Arrobj" } */
In fact, the above results have been processed two times:
1. Add a \ n to the end of each ' {', '} ', and ', ' after value
2. Add a \ t (Tab tab, which is the third parameter value in this example) to the front of each first-level key, and the two-level key is preceded by two \ T, and so on.
To verify the above two points more clearly, perform the following tests:
var Jsonobj = {"Name": "Value", "arr": [' str1 ', ' str2 ', {' arrobj ': ' arrobj 'null, ' \ t '). Replace (/\n/g, ' |-- N--| '). Replace (/\t/g, ' |--t--| ' ); //result for "{|--n--| | --t--| " Name ":" Value ", |--n--| | --t--| " Arr ": [|--n--| | --t--| | --t--| " Str1 ", |--n--| | --t--| | --t--| " Str2 ", |--n--| | --t--| | --t--| {|--n--| | --t--| | --t--| | --t--| " Arrobj ":" Arrobj "|--n--| | --t--| | --t--|}| --n--| | --t--|]| --n--|} "
Json.stringify ()