The JSON standard defines objects in one way and the ECMAScript (JavaScript) standard defines it in another.
It is often said that JSON objects are a subset of JavaScript objects, is this true?
Is every JSON object also a valid JavaScript object?
The JSON standard defines objects in one way and the ECMAScript (JavaScript) standard defines it in another.
It is often said that JSON objects are a subset of JavaScript objects, is this true?
Is every JSON object also a valid JavaScript object?
Update 2019: the answer is now YES as of this proposal and JavaScript versions following ECMAScript 2019 (including) will be proper supersets.
The answer is "no". There are cases when JSON object won't be valid for JavaScript. JSON is NOT a JavaScript subset.
JSON
That is: due to JSON specification, you can safely use such characters, as U+2028 in any string. It is a unicode whitespace character. Not control or other special character.
JavaScript
Well, now in JavaScript. ECMA-262 has a little difference in its definition of strings. In section 7.8.4 there is a thing, that string can contain all things except quote, a backslash or a line terminator. Now what's line terminator? It's in section 7.3 :
As you can see, in JavaScript symbols U+2028 and U+2029 are not allowed.
This is a sample, but since we have at least one case of difference, it's well-enough to realize that answer is no
Image source & full description: timelessrepo
First, some precaution should be taken when using the term "JSON object":
If you want, "JSON object" can refer to the object that a JSON text represents. Even the JSON specification defines what "object" means:
An object is an unordered collection of zero or more name/value pairs
This is just an intent, as JSON itself is not a processing language: it does not parse text into objects.
Not all JSON texts represent objects (e.g. they can represent string or number literals), so speaking of "JSON object" does have some additional value: it would be short for "a JSON text that represents an object".
It's like saying "email notification". Email is a communication mechanism, and one particular email can represent a message to you. It might represent a notification of something, but does not have to be.
While "JSON objects" might be a valid term, it should not be used for JavaScript objects. JSON can be used in many language platforms, so the historic connection with JavaScript should really be laid aside.
JavaScript object literals have other syntax rules than JSON, so they should not be confused. For instance:
[1, , 2]
);U+2028
and U+2029
characters in strings. Before EcmaScript2019, these characters needed to be escaped in JavaScript. This difference is taken away with EcmaScript2019;© 2022 - 2024 — McMap. All rights reserved.
{"x": 1e99999}
is a valid JavaScript object in terms of syntax but out of bounds for JavaScript semantically (since doubles can't hold numbers that big). – Federicofedirko