Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 438
Benjamin Gruenbaum Avatar asked May 20 '14 06:05

Benjamin Gruenbaum


People also ask

Are JSON objects the same as JavaScript objects?

An Object literal is when you declare an Object in JavaScript code which is a variable that stores data in key-value pairs, while JSON stands for JavaScript Object Notation and it's a language-agnostic format for storing and transferring data that is based on JavaScript Objects.

Is all JSON valid JavaScript?

Any JSON text is a valid JavaScript expression, but only in JavaScript engines that have implemented the proposal to make all JSON text valid ECMA-262.

What is valid JSON object?

JSON objects are written in key/value pairs. JSON objects are surrounded by curly braces { } . Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon. Each key/value pair is separated by a comma.

Is JavaScript and JSON same?

The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only.


1 Answers

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

like image 72
Alma Do Avatar answered Sep 24 '22 10:09

Alma Do