Serializing a value

suggest change

A JavaScript value can be converted to a JSON string using the JSON.stringify function.

JSON.stringify(value[, replacer[, space]])
  1. value The value to convert to a JSON string.

    /* Boolean */  JSON.stringify(true)             // 'true'
    /* Number  */  JSON.stringify(12)               // '12'
    /* String  */  JSON.stringify('foo')            // '"foo"'
    /* Object  */  JSON.stringify({})               // '{}'
                   JSON.stringify({foo: 'baz'})     // '{"foo":"baz"}'
    /* Array   */  JSON.stringify([1, true, 'foo']) // '[1,true,"foo"]'
    /* Date    */  JSON.stringify(new Date())       // an ISO-8601 string, such as '"2016-08-06T17:25:23.588Z"'
    /* Symbol  */  JSON.stringify({x:Symbol()})     // '{}'
    
  2. replacer A function that alters the stringification process, or an array of strings and numbers used as a whitelist of property names. If this value is null or is not provided, the enumerable own string-keyed properties are included. Functions, symbols, and undefined properties are omitted.

    // replacer as a function
    function replacer (key, value) {
        // Filtering out properties
        if (typeof value === "string") {
            return
        }    
        return value
    }
    
    const foo = { foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7 }
    JSON.stringify(foo, replacer)
    // -> '{"week":45,"month":7}'
    
    // replacer as an array
    JSON.stringify(foo, ['foundation', 'week', 'month'])
    // -> '{"foundation":"Mozilla","week":45,"month":7}'
    // only the `foundation`, `week`, and `month` properties are kept
    
  3. space For readability, the number of spaces used for indentation may be specified as the third parameter.

    JSON.stringify({x: 1, y: 1}, null, 2)  // 2 space characters will be used for indentation
    /* output:
    {
      "x": 1,
      "y": 1
    }
    */
    

    Alternatively, a string value can be provided to use for indentation. For example, passing '\t' will cause the tab character to be used for indentation.

    JSON.stringify({x: 1, y: 1}, null, '\t')
    /* output:
    {
    	"x": 1,
    	"y": 1
    }
    */
    

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents