25.5 The JSON Object
The JSON object:
- is %JSON%.
- is the initial value of the
"JSON" property of theglobal object . - is an
ordinary object . - contains two functions,
parse
andstringify
, that are used to parse and construct JSON texts. - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - does not have a [[Construct]] internal method; it cannot be used as a
constructor with thenew
operator. - does not have a [[Call]] internal method; it cannot be invoked as a function.
The JSON Data Interchange Format is defined in ECMA-404. The JSON interchange format used in this specification is exactly that described by ECMA-404. Conforming implementations of JSON.parse
and JSON.stringify
must support the exact interchange format described in the ECMA-404 specification without any deletions or extensions to the format.
25.5.1 JSON.parse ( text [ , reviver ] )
This function parses a JSON text (a JSON-formatted String) and produces an
The optional reviver parameter is a function that takes two parameters, key and value. It can filter and transform the results. It is called with each of the key/value pairs produced by the parse, and its return value is used instead of the original value. If it returns what it received, the structure is not modified. If it returns
- Let jsonString be ?
ToString (text). - Parse
StringToCodePoints (jsonString) as a JSON text as specified in ECMA-404. Throw aSyntaxError exception if it is not a valid JSON text as defined in that specification. - Let scriptString be the
string-concatenation of"(" , jsonString, and");" . - Let script be
ParseText (StringToCodePoints (scriptString),Script ). - NOTE: The
early error rules defined in13.2.5.1 have special handling for the above invocation ofParseText . Assert : script is aParse Node .- Let completion be
Completion (Evaluation of script). - NOTE: The
PropertyDefinitionEvaluation semantics defined in13.2.5.5 have special handling for the above evaluation. - Let unfiltered be completion.[[Value]].
Assert : unfiltered is either a String, a Number, a Boolean, an Object that is defined by either anArrayLiteral or anObjectLiteral , ornull .- If
IsCallable (reviver) istrue , then- Let root be
OrdinaryObjectCreate (%Object.prototype% ). - Let rootName be the empty String.
- Perform !
CreateDataPropertyOrThrow (root, rootName, unfiltered). - Return ?
InternalizeJSONProperty (root, rootName, reviver).
- Let root be
- Else,
- Return unfiltered.
The
Valid JSON text is a subset of the ECMAScript
However, because JSON.parse
, the same source text can produce different results when evaluated as a JSON.parse
, means that not all texts accepted by JSON.parse
are valid as a
25.5.1.1 InternalizeJSONProperty ( holder, name, reviver )
The abstract operation InternalizeJSONProperty takes arguments holder (an Object), name (a String), and reviver (a
This algorithm intentionally does not throw an exception if either [[Delete]] or
It performs the following steps when called:
- Let val be ?
Get (holder, name). - If val
is an Object , then- Let isArray be ?
IsArray (val). - If isArray is
true , then- Let len be ?
LengthOfArrayLike (val). - Let I be 0.
- Repeat, while I < len,
- Let prop be !
ToString (𝔽 (I)). - Let newElement be ?
InternalizeJSONProperty (val, prop, reviver). - If newElement is
undefined , then- Perform ? val.[[Delete]](prop).
- Else,
- Perform ?
CreateDataProperty (val, prop, newElement).
- Perform ?
- Set I to I + 1.
- Let prop be !
- Let len be ?
- Else,
- Let keys be ?
EnumerableOwnProperties (val,key ). - For each String P of keys, do
- Let newElement be ?
InternalizeJSONProperty (val, P, reviver). - If newElement is
undefined , then- Perform ? val.[[Delete]](P).
- Else,
- Perform ?
CreateDataProperty (val, P, newElement).
- Perform ?
- Let newElement be ?
- Let keys be ?
- Let isArray be ?
- Return ?
Call (reviver, holder, « name, val »).
It is not permitted for a conforming implementation of JSON.parse
to extend the JSON grammars. If an implementation wishes to support a modified or extended JSON interchange format it must do so by defining a different parse function.
In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.
25.5.2 JSON.stringify ( value [ , replacer [ , space ] ] )
This function returns a String in UTF-16 encoded JSON format representing an
It performs the following steps when called:
- Let stack be a new empty
List . - Let indent be the empty String.
- Let PropertyList be
undefined . - Let ReplacerFunction be
undefined . - If replacer
is an Object , then- If
IsCallable (replacer) istrue , then- Set ReplacerFunction to replacer.
- Else,
- Let isArray be ?
IsArray (replacer). - If isArray is
true , then- Set PropertyList to a new empty
List . - Let len be ?
LengthOfArrayLike (replacer). - Let k be 0.
- Repeat, while k < len,
- Let prop be !
ToString (𝔽 (k)). - Let v be ?
Get (replacer, prop). - Let item be
undefined . - If v
is a String , then- Set item to v.
- Else if v
is a Number , then- Set item to !
ToString (v).
- Set item to !
- Else if v
is an Object , then- If v has a [[StringData]] or [[NumberData]] internal slot, set item to ?
ToString (v).
- If v has a [[StringData]] or [[NumberData]] internal slot, set item to ?
- If item is not
undefined and PropertyList does not contain item, then- Append item to PropertyList.
- Set k to k + 1.
- Let prop be !
- Set PropertyList to a new empty
- Let isArray be ?
- If
- If space
is an Object , then - If space
is a Number , then- Let spaceMV be !
ToIntegerOrInfinity (space). - Set spaceMV to
min (10, spaceMV). - If spaceMV < 1, let gap be the empty String; otherwise let gap be the String value containing spaceMV occurrences of the code unit 0x0020 (SPACE).
- Let spaceMV be !
- Else if space
is a String , then- If the length of space ≤ 10, let gap be space; otherwise let gap be the
substring of space from 0 to 10.
- If the length of space ≤ 10, let gap be space; otherwise let gap be the
- Else,
- Let gap be the empty String.
- Let wrapper be
OrdinaryObjectCreate (%Object.prototype% ). - Perform !
CreateDataPropertyOrThrow (wrapper, the empty String, value). - Let state be the
JSON Serialization Record { [[ReplacerFunction]]: ReplacerFunction, [[Stack]]: stack, [[Indent]]: indent, [[Gap]]: gap, [[PropertyList]]: PropertyList }. - Return ?
SerializeJSONProperty (state, the empty String, wrapper).
The
JSON structures are allowed to be nested to any depth, but they must be acyclic. If value is or contains a cyclic structure, then this function must throw a
a = [];
a[0] = a;
my_text = JSON.stringify(a); // This must throw a TypeError.
Symbolic primitive values are rendered as follows:
-
The
null value is rendered in JSON text as the String value"null" . -
The
undefined value is not rendered. -
The
true value is rendered in JSON text as the String value"true" . -
The
false value is rendered in JSON text as the String value"false" .
String values are wrapped in QUOTATION MARK ("
) code units. The code units "
and \
are escaped with \
prefixes. Control characters code units are replaced with escape sequences \u
HHHH, or with the shorter forms, \b
(BACKSPACE), \f
(FORM FEED), \n
(LINE FEED), \r
(CARRIAGE RETURN), \t
(CHARACTER TABULATION).
Values that do not have a JSON representation (such as
An object is rendered as U+007B (LEFT CURLY BRACKET) followed by zero or more properties, separated with a U+002C (COMMA), closed with a U+007D (RIGHT CURLY BRACKET). A property is a quoted String representing the
25.5.2.1 JSON Serialization Record
A JSON Serialization Record is a
JSON Serialization Records have the fields listed in
Field Name | Value | Meaning |
---|---|---|
[[ReplacerFunction]] | a |
A function that can supply replacement values for object properties (from JSON.stringify's replacer parameter). |
[[PropertyList]] | either a |
The names of properties to include when serializing a non-array object (from JSON.stringify's replacer parameter). |
[[Gap]] | a String | The unit of indentation (from JSON.stringify's space parameter). |
[[Stack]] | a |
The set of nested objects that are in the process of being serialized. Used to detect cyclic structures. |
[[Indent]] | a String | The current indentation. |
25.5.2.2 SerializeJSONProperty ( state, key, holder )
The abstract operation SerializeJSONProperty takes arguments state (a
- Let value be ?
Get (holder, key). - If value
is an Object or valueis a BigInt , then- Let toJSON be ?
GetV (value,"toJSON" ). - If
IsCallable (toJSON) istrue , then- Set value to ?
Call (toJSON, value, « key »).
- Set value to ?
- Let toJSON be ?
- If state.[[ReplacerFunction]] is not
undefined , then- Set value to ?
Call (state.[[ReplacerFunction]], holder, « key, value »).
- Set value to ?
- If value
is an Object , then- If value has a [[NumberData]] internal slot, then
- Set value to ?
ToNumber (value).
- Set value to ?
- Else if value has a [[StringData]] internal slot, then
- Set value to ?
ToString (value).
- Set value to ?
- Else if value has a [[BooleanData]] internal slot, then
- Set value to value.[[BooleanData]].
- Else if value has a [[BigIntData]] internal slot, then
- Set value to value.[[BigIntData]].
- If value has a [[NumberData]] internal slot, then
- If value is
null , return"null" . - If value is
true , return"true" . - If value is
false , return"false" . - If value
is a String , returnQuoteJSONString (value). - If value
is a Number , then - If value
is a BigInt , throw aTypeError exception. - If value
is an Object andIsCallable (value) isfalse , then- Let isArray be ?
IsArray (value). - If isArray is
true , return ?SerializeJSONArray (state, value). - Return ?
SerializeJSONObject (state, value).
- Let isArray be ?
- Return
undefined .
25.5.2.3 QuoteJSONString ( value )
The abstract operation QuoteJSONString takes argument value (a String) and returns a String. It wraps value in 0x0022 (QUOTATION MARK) code units and escapes certain other code units within it. This operation interprets value as a sequence of UTF-16 encoded code points, as described in
- Let product be the String value consisting solely of the code unit 0x0022 (QUOTATION MARK).
- For each code point C of
StringToCodePoints (value), do- If C is listed in the “Code Point” column of
Table 76 , then- Set product to the
string-concatenation of product and the escape sequence for C as specified in the “Escape Sequence” column of the corresponding row.
- Set product to the
- Else if C has a numeric value less than 0x0020 (SPACE) or C has the same numeric value as a
leading surrogate ortrailing surrogate , then- Let unit be the code unit whose numeric value is the numeric value of C.
- Set product to the
string-concatenation of product andUnicodeEscape (unit).
- Else,
- Set product to the
string-concatenation of product andUTF16EncodeCodePoint (C).
- Set product to the
- If C is listed in the “Code Point” column of
- Set product to the
string-concatenation of product and the code unit 0x0022 (QUOTATION MARK). - Return product.
Code Point | Unicode Character Name | Escape Sequence |
---|---|---|
U+0008 | BACKSPACE |
\b
|
U+0009 | CHARACTER TABULATION |
\t
|
U+000A | LINE FEED (LF) |
\n
|
U+000C | FORM FEED (FF) |
\f
|
U+000D | CARRIAGE RETURN (CR) |
\r
|
U+0022 | QUOTATION MARK |
\"
|
U+005C | REVERSE SOLIDUS |
\\
|
25.5.2.4 UnicodeEscape ( C )
The abstract operation UnicodeEscape takes argument C (a code unit) and returns a String. It represents C as a Unicode escape sequence. It performs the following steps when called:
- Let n be the numeric value of C.
Assert : n ≤ 0xFFFF.- Let hex be the String representation of n, formatted as a lowercase hexadecimal number.
- Return the
string-concatenation of the code unit 0x005C (REVERSE SOLIDUS),"u" , andStringPad (hex, 4,"0" ,start ).
25.5.2.5 SerializeJSONObject ( state, value )
The abstract operation SerializeJSONObject takes arguments state (a
- If state.[[Stack]] contains value, throw a
TypeError exception because the structure is cyclical. - Append value to state.[[Stack]].
- Let stepback be state.[[Indent]].
- Set state.[[Indent]] to the
string-concatenation of state.[[Indent]] and state.[[Gap]]. - If state.[[PropertyList]] is not
undefined , then- Let K be state.[[PropertyList]].
- Else,
- Let K be ?
EnumerableOwnProperties (value,key ).
- Let K be ?
- Let partial be a new empty
List . - For each element P of K, do
- Let strP be ?
SerializeJSONProperty (state, P, value). - If strP is not
undefined , then- Let member be
QuoteJSONString (P). - Set member to the
string-concatenation of member and":" . - If state.[[Gap]] is not the empty String, then
- Set member to the
string-concatenation of member and the code unit 0x0020 (SPACE).
- Set member to the
- Set member to the
string-concatenation of member and strP. - Append member to partial.
- Let member be
- Let strP be ?
- If partial is empty, then
- Let final be
"{}" .
- Let final be
- Else,
- If state.[[Gap]] is the empty String, then
- Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with the code unit 0x002C (COMMA). A comma is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"{" , properties, and"}" .
- Else,
- Let separator be the
string-concatenation of the code unit 0x002C (COMMA), the code unit 0x000A (LINE FEED), and state.[[Indent]]. - Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with separator. The separator String is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"{" , the code unit 0x000A (LINE FEED), state.[[Indent]], properties, the code unit 0x000A (LINE FEED), stepback, and"}" .
- Let separator be the
- If state.[[Gap]] is the empty String, then
- Remove the last element of state.[[Stack]].
- Set state.[[Indent]] to stepback.
- Return final.
25.5.2.6 SerializeJSONArray ( state, value )
The abstract operation SerializeJSONArray takes arguments state (a
- If state.[[Stack]] contains value, throw a
TypeError exception because the structure is cyclical. - Append value to state.[[Stack]].
- Let stepback be state.[[Indent]].
- Set state.[[Indent]] to the
string-concatenation of state.[[Indent]] and state.[[Gap]]. - Let partial be a new empty
List . - Let len be ?
LengthOfArrayLike (value). - Let index be 0.
- Repeat, while index < len,
- Let strP be ?
SerializeJSONProperty (state, !ToString (𝔽 (index)), value). - If strP is
undefined , then- Append
"null" to partial.
- Append
- Else,
- Append strP to partial.
- Set index to index + 1.
- Let strP be ?
- If partial is empty, then
- Let final be
"[]" .
- Let final be
- Else,
- If state.[[Gap]] is the empty String, then
- Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with the code unit 0x002C (COMMA). A comma is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"[" , properties, and"]" .
- Else,
- Let separator be the
string-concatenation of the code unit 0x002C (COMMA), the code unit 0x000A (LINE FEED), and state.[[Indent]]. - Let properties be the String value formed by concatenating all the element Strings of partial with each adjacent pair of Strings separated with separator. The separator String is not inserted either before the first String or after the last String.
- Let final be the
string-concatenation of"[" , the code unit 0x000A (LINE FEED), state.[[Indent]], properties, the code unit 0x000A (LINE FEED), stepback, and"]" .
- Let separator be the
- If state.[[Gap]] is the empty String, then
- Remove the last element of state.[[Stack]].
- Set state.[[Indent]] to stepback.
- Return final.
The representation of arrays includes only the elements in the array.length
(exclusive). Properties whose keys are not
25.5.3 JSON [ @@toStringTag ]
The initial value of the
This property has the attributes { [[Writable]]: