1

Possible Duplicate:
JSON Spec - does the key have to be surrounded with quotes?

Which is the correct syntax?

{ key: "value" } or { "key": "value" }?

I've seen it both ways and in my tests both work, but I'm just curious which one is syntactically correct?

Community
  • 1
  • 1
FatalKeystroke
  • 2,882
  • 7
  • 23
  • 35
  • Have a look at this thread: http://stackoverflow.com/questions/2067974/in-json-why-is-each-name-quoted Cheers – Cherusker Oct 08 '12 at 17:58

2 Answers2

8

JSON requires keys to be quoted. JavaScript does not. So for JSON, your second example is correct.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • JavaScript does not, so long as the key is appropriate for a JavaScript label (alphanumeric, initial alpha, a few other other things). – Michael Lorton Oct 08 '12 at 17:59
  • To expand on @Malvolio. You also cannot have Javascript reserved words without quotes. You can't have { undefined : "value" }, as an example. I usually just include the quotes to keep it consistent. – Ryan O'Neill Oct 08 '12 at 18:06
  • @RyanO'Neill: The spec *(ECMAScript 5 anyway)* lets you have reserved words without quotes. Just some older browsers didn't allow it. And `undefined` is actually not reserved. It's a valid identifier. – I Hate Lazy Oct 08 '12 at 18:27
  • 1
    @user1689607 -- if you write something like `{ function : 6, undefined : "value" }` you deserve all the terrible things that will undoubtedly happen to you! – Michael Lorton Oct 09 '12 at 02:16
  • Not sure, exactly, but I have have faith in code karma. What goes around comes around. – Michael Lorton Oct 09 '12 at 06:09
  • Notwithstanding from the aforementioned browser quirks, nothing terrible will happen. No need for FUD. – I Hate Lazy Oct 09 '12 at 13:01
1

They are both valid notation for a javascript object. Only the fully-quoted second version is valid JSON.

See the spec and this web-based linter.

jbabey
  • 45,965
  • 12
  • 71
  • 94