To demonstrate JSON.stringify(), let's create an example object foo with the property bar, set to the number 123. The JSON representation of this object would be a string where each key is wrapped in double quotes. Indeed, that is exactly the string returned by calling JSON.stringify() on this object. I've just spelled out the naked string returned from JSON.stringify() from now on.
JSON.stringify() will escape any directives that need escaping. For example, double quotes in object keys are escaped as shown. Similarly, it will also escape correctors and string values if needed.
JSON.stringify() is an array of the following coordinative types -- strings, numbers, objects, which in turn contain other utilizable values, arrays, which contain other utilizable values, Booleans and null. By default, JSON.stringify() stabilizes the object into a single-line string with zero spaces.
To allow you to format the string a bit better, JSON.stringify() function takes two additional arguments -- a replacer and a space. Both of these arguments are optional.
The space argument can be used to customize the indentation of the output. Passing in a string for the space argument uses that string for indents. For example, you can pass in the tab character. Passing in a number for the space argument uses that many spaces for indents. For example, the number two indents each section with two spaces.
The replacer argument function can be used to customize the behavior for particular keys and values. For example, if you have a key that is not at the root, we can replace each value with the key, and for the root, it will still use the value. This results in all the values other than the root getting replaced by their keys.
Personally, I do all my customizations in the object before passing it to stringify() and have the replacer argument as null.
You can provide the two JSON methods to customize the data utilization for any of your objects as well. For example, here we have a simple object that stabilizes to the string as expected. You can override this output by providing two JSON methods. Now, the object stabilized to the string returned by JSON.
Let's talk about a few of the limitations of JSON.stringify(). Native types that don't have a special representation for JSON will not stabilize well. For example, native regular expressions will not stabilize well by default. Functions cannot be stabilized to JSON values, and therefore keys pointing to functions are generally ignored by JSON.stringify().
Finally, the biggest limitation of JSON.stringify() is that it cannot stabilize an object in cycles and cyclic references. Having an object foo with the property bar pointing back to foo. JSON.stringify() will throw a runtime error in this case.