stringify

Table of contents

  1. 1. Summary
  2. 2. Syntax
  3. 3. Parameters
  4. 4. Description
    1. 4.1. space argument
    2. 4.2. toJSON behavior

Summary

Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

Method of JSON
Implemented in JavaScript 1.7
ECMAScript Edition ECMAScript 5th Edition

Syntax

JSON.stringify(value[, replacer [, space]])

Parameters

value
The value to convert to a JSON string.
replacer
If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string.
A detailed description of the replacer function is provided in Using native JSON#The_replacer_parameter.
space
Causes the resulting string to be pretty-printed.

Description

JSON.stringify converts an object to JSON notation representing it.

assert(JSON.stringify({}) === '{}');
assert(JSON.stringify(true) === 'true');
assert(JSON.stringify("foo") === '"foo"');
assert(JSON.stringify([1, "false", false]) === '[1,"false",false]');
assert(JSON.stringify({ x: 5 }) === '{"x":5}');
JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'

Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.

Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.

If undefined, a function, or an XML value is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).

space argument

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'

Using a tab character mimics standard pretty-print appearance:

JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
// returns the string:
// '{            \
//     "uno": 1, \
//     "dos": 2  \
// }'

 

toJSON behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized. For example:

var x = {
  foo: 'foo',
  toJSON: function () {
    return 'bar';
  }
};
var json = JSON.stringify({x: x});

json will be the string '{"x":"bar"}'.

Tags (0)

Edit tags
  • No tags

Attachments (0)

 

Attach file