Are all JSON objects also valid JavaScript objects?

前端 未结 2 1968
小鲜肉
小鲜肉 2020-11-28 09:32

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 Java

2条回答
  •  遥遥无期
    2020-11-28 09:52

    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.

    JSON versus JavaScript object literals

    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:

    • JSON requires that strings are wrapped in double quotes, while JavaScript object literals may have non-quoted property names, and single quoted strings;
    • JSON is restricted to a few data types, while JavaScript object literals may include other data types and notations, like regular expression literals, template literals, functions, ...etc;
    • JSON does not allow empty elements in array literals, while JavaScript literals do (e.g. [1, , 2]);
    • JSON allows 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;

提交回复
热议问题