JSON syntax for property names

@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).

Leave a Comment