Using JavaScript's JSON.stringify

The JSON.stringify method converts a JavaScript value into a JSON string. It is typically used to convert JavaScript arrays or objects to JSON, although it can also be used with simple data types like strings and numbers.

First let's convert a JavaScript array to JSON:

var ar = ['apple', 'orange', 'banana', 'strawberry'];
var json = JSON.stringify(ar); // '["apple","orange","banana","strawberry"]'

In the result displayed in code comments, we can see that our array is now a string, that single quotes have been converted to double quotes,[1] and that white space has been removed.

JavaScript Object Literal to JSON

Next, let's convert a basic JavaScript object literal to JSON:

var book = {
    title: 'JavaScript: The Definitive Guide',
    author: 'David Flanagan',
    edition: 6

var json = JSON.stringify(book);
// {"title":"JavaScript: The Definitive Guide","author":"David Flanagan","edition":6}

We use console.log to display the JSON string where we can see that our property names as well as their values have been enclosed in double quotes. Read below how you can make the output of JSON.stringify more readable with an indent argument.

JSON.stringify with Unsupported Data Types

Some data types supported by JavaScript are not valid JSON. Strings, numbers, booleans, null, arrays, and objects are supported. Date objects, regular expressions, undefined, and functions are not. How JSON.stringify handles unsupported data types varies somewhat depending upon whether they are contained in an object or an array. We demonstrate with examples.

We apply JSON.stringify to a relatively complex JavaScript object that includes some unsupported data types. Let's see what happens:

var myObject = {
    num: 50,
    str: 'A string here',
    today: new Date(),
    ar: ['one', 'two', 'three'],
    obj: {
        min: 2,
        max: 1000,
        bool: true,
        o: null,
        val: undefined,
        re: /^\d+$/,
        fn: function(val) {
            // code here

var json = JSON.stringify(myObject);
{"num":50,"str":"A string here","today":"2015-02-02T02:49:21.520Z",

In the output of console.log we can see that the date object has been converted to a string,[2] and the regular expression has been converted to an empty object. The properties with undefined and function values have been removed from the result altogether.

JSON.stringify has an optional second argument, referred to as a filter or replacer, that can be used to screen or modify the data passed to it. Another page demonstrates and describes how this can be implemented.

JSON.stringify with Arrays

As mentioned above, JSON.stringify handles some unsupported data types differently when they are contained in arrays. Let's see how using this example:

var ar = ['Hello', 4, true, null, undefined, new Date(), /^\d+$/,
        function() { alert('Yo'); }, { x: 2, y: 8 } ];

var json = JSON.stringify(ar);

Notice that while the date and regular expression objects were handled the same for both our object and array examples, the elements containing undefined and function values were not removed, as they were in the object, but instead converted to null. This preserves the indexes of the array elements as well as the array's length.

Indent or Space Argument

The output of JSON.stringify contains no white space by default, making it compact for data transmission but difficult to read. An optional third argument to stringify allows you to introduce white space to make it more readable. The following shows the result of using an indent of 4 for the myObject example from above:[3]

// using indent argument
var json = JSON.stringify(myObject, null, 4);
/* output of console.log with indent of 4
    "num": 50,
    "str": "A string here",
    "today": "2015-02-02T17:05:30.684Z",
    "ar": [
    "obj": {
        "min": 2,
        "max": 1000,
        "bool": true,
        "o": null,
        "re": {}

But what about null in that second position? The optional second argument provides another way to influence the results of the stringify method. Find out how you can use the filter or replacer option to further control the output of JSON.stringify.

Back to top

  1. Single quotes are not valid in JSON. ^
  2. The date object has a built-in toJSON method for this purpose. Find out about the toJSON method and how you can write custom toJSON methods for your objects. ^
  3. Find out more about the space argument at MDN. ^