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())       // '"2016-08-06T17:25:23.588Z"'
    /* Symbol  */  JSON.stringify({x:Symbol()})     // '{}'
  2. replacer A function that alters the behaviour of the stringification process or an array of String and Number objects that serve as a whitelist for filtering the properties of the value object to be included in the JSON string. If this value is null or is not provided, all properties of the object are included in the resulting JSON string.
    // replacer as a function
    function replacer (key, value) {
        // Filtering out properties
        if (typeof value === "string") {
            return
        }    
        return value
    }
    
    var 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