Categories
character-encoding encoding javascript json

Are all JSON objects also valid JavaScript objects?

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.


TL;DR

The answer is “no”. There are cases when JSON object won’t be valid for JavaScript. JSON is NOT a JavaScript subset.

“Little” difference

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.

enter image description here

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 :

  • \u000A – Line Feed
  • \u000D – Carriage Return
  • \u2028 – Line separator
  • \u2029 – Paragraph separator

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