1

Possible Duplicate:
What is the difference between object keys with quotes and without quotes?

What is the difference between a and b as below?

var a = {foo : "bar"};
var b = {"foo" : "bar"};
Community
  • 1
  • 1
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • See http://stackoverflow.com/questions/4348478/is-difference-between-object-keys-with-quotes-and-without-quotes – Donovan Aug 28 '11 at 10:10
  • Stack Overflow requires you to [do some effort](http://stackoverflow.com/questions/how-to-ask) before asking questions, have you looked into the Javascript standard? – Tamara Wijsman Aug 28 '11 at 10:11
  • It was already said, but I say it again: There is no JSON in your snippet. – Felix Kling Aug 28 '11 at 10:19
  • @Felix Isn't b the JSON format? – xdazz Aug 28 '11 at 10:24
  • 1
    No, we are in the context of JavaScript. It is still a JavaScript object literal. If you'd put `{"foo" : "bar"}` in a string or in a new file, then yes, it would be JSON (more or less by chance). JSON is a data exchange format. It looks very similar to JavaScript object literals, but they are not the same. It is more like XML. Consider a language where you could write `var s = ;`. Is this XML? No. – Felix Kling Aug 28 '11 at 10:28
  • @Felix Thanks for your explain. For example, can we say the ajax response is json format, the variable used to hold the response is json format ? – xdazz Aug 28 '11 at 10:47
  • If you get the data as response from an Ajax call, then yes, you can say the variable which is holding the response text contains JSON. But once you have parsed that JSON into a JavaScript object, you don't have JSON anymore. – Felix Kling Aug 28 '11 at 10:58

3 Answers3

6

Both are valid JavaScript object literals, and evaluate to different objects with properties called foo, with a.foo == b.foo being true.

Since you tagged this , the first statement is invalid JSON because keys need to be strings (aside from the var a declaration).

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
5

There is no difference.

A key in an object literal can be an identifier or a string literal. You can use characters in a string that you can't use in an identifier, but foo doesn't contain any of those.

(As an aside, if you were writing JSON rather than JS, then the key would have to be a string)

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

They are the same.

The quoted syntax allows to set keys that are not valid identifiers (like foo bar) or that are reserved keywords (like for).

JSON only allows the quoted syntax.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194