Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...