Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - JSON syntax for property names

What is the correct syntax to create objects in javascript that will work across the majority of web browsers (by that I mean : IE 6+, Firefox 2+, Opera 9+ )

Is this valid

var a = {
  "class": "Person",
  "name": "William Shakespeare",
  "birthday": -12802392000000,
  "nickname": "Bill"
};

Or is this:

var a = {
  class: "Person",
  name: "William Shakespeare",
  birthday: -12802392000000,
  nickname: "Bill"
};

And what is the difference between the two?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

@AndreasN is correct: the JSON specification dictates the use of quotes in order for it to actually be JSON. If you don't use quotes, it may be a valid object literal in Javascript, but it is not JSON. Other services besides browser-side Javascript use JSON (e.g. webservices using php, Java, etc.) and if you construct a string that lacks the quotes, there is no guarantee that it will be parsed correctly -- although I suspect most implementations would be robust enough to do so.

FYI it is dangerous in Javascript to directly use eval() on JSON strings from sources which you cannot prevent malicious attacks. Again, see the JSON site which gives more of an explanation as well as a very short javascript file which safely parses JSON strings into Javascript objects.

edit: I guess technically your original question is not about JSON but rather the Javascript's syntax for object literals. The difference is that objects constructable from a JSON string will exclude many other possible object literals, e.g.:

var a = {cat: "meow", dog: "woof"};
var aname = {cat: "Garfield", dog: "Odie"};
var b = {
  counter: 0,
  pow: function(x) { return x+1; },
  zap: function(y) { return (counter += y); }
};
var c = {
  all: [a,aname],
  animals: a,
  names: aname,
};

Object literals "a" and "aname" can be expressed in JSON (by adding quotes to the property names). But object literals "b" and "c" cannot. Object literal "b" contains functions (not allowed in JSON). Object literal "c" above contains references to other variables in a way that is not representable in JSON because some of the references are shared. If you make a change to c.names it will also change c.all[1] since they share a reference to the same variable. JSON can only express objects that have a tree structure (e.g. each sub-element of the overall object is independent).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...