287

Example: Is the following code valid against the JSON Spec?

{
    precision: "zip"
}

Or should I always use the following syntax? (And if so, why?)

{
    "precision": "zip"
}

I haven't really found something about this in the JSON specifications. Although they use quotes around their keys in their examples.

Community
  • 1
  • 1
christianvuerings
  • 22,500
  • 4
  • 23
  • 19

8 Answers8

176

Yes, you need quotation marks. This is to make it simpler and to avoid having to have another escape method for javascript reserved keywords, ie {for:"foo"}.

cobbal
  • 69,903
  • 20
  • 143
  • 156
  • 14
    The quotes are not simpler in many situations, such as config files that are edited by hand. The unfortunate thing about JSON being used (and misused) as an almost universal interchange format is that it has features specific to Javascript. – miguel Jan 13 '15 at 22:56
  • 16
    Real reason - check this answer too - http://stackoverflow.com/questions/4201441/is-there-any-practical-reason-to-use-quoted-strings-for-json-keys – TechMaze Jul 01 '15 at 00:07
  • 3
    Tl;dr: they didn't want to deal with the ECMAScript limitation on (unquoted) reserved keywords as keys, so they just required quoting all keys. – BallpointBen Aug 21 '18 at 23:01
143

You are correct to use strings as the key. Here is an excerpt from RFC 4627 - The application/json Media Type for JavaScript Object Notation (JSON)

2.2. Objects

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

object = begin-object [ member *( value-separator member ) ] end-object

member = string name-separator value

[...]

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. [...]

string = quotation-mark *char quotation-mark

quotation-mark = %x22 ; "

Read the whole RFC here.

Community
  • 1
  • 1
PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
16

From 2.2. Objects

An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string.

and from 2.5. Strings

A string begins and ends with quotation marks.

So I would say that according to the standard: yes, you should always quote the key (although some parsers may be more forgiving)

Cebjyre
  • 6,552
  • 3
  • 32
  • 57
10

Not if you use JSON5

For regular JSON, yes keys must be quoted. But if you need otherwise, checkout widely used JSON5, which is so-named because is a superset of JSON that allows ES5 syntax, including:

  • unquoted property keys
  • single-quoted, escaped and multi-line strings
  • alternate number formats
  • comments
  • extra whitespace

The JSON5 reference implementation (json5 npm package) provides a JSON5 object that has parse and stringify methods with the same args and semantics as the built-in JSON object.

widely used, and depended on by many high profile projects

JSON5 was started in 2012, and as of 2022, now gets >65M downloads/week, ranks in the top 0.1% of the most depended-upon packages on npm, and has been adopted by major projects like Chromium, Next.js, Babel, Retool, WebStorm, and more. It's also natively supported on Apple platforms like MacOS and iOS.

~ json5.org homepage

Inigo
  • 12,186
  • 5
  • 41
  • 70
  • 3
    wow saved my day... the amount of time i spent on this BS.. and JSON5 parsing solved it – RanH Jan 01 '23 at 14:48
9

Yes, quotes are mandatory. http://json.org/ says:

string
    ""
    " chars "
0

In your situation, both of them are valid, meaning that both of them will work.

However, you still should use the one with quotation marks in the key names because it is more conventional, which leads to more simplicity and ability to have key names with white spaces etc.

Therefore, use the one with the quotation marks.

edit// check this: What is the difference between JSON and Object Literal Notation?

wolfenblut
  • 131
  • 1
  • 11
  • 2
    It might be more conventional, but it's also more typing. – Martin Rattigan Nov 30 '21 at 23:43
  • Of the two options in OP, only the one with the quotes is valid *JSON*. The other one is not. They aren't interchangeable. The only place they both work is as JS code which is *not* JSON. [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131) So, the quotes aren't "more conventional" - they are *the only* convention in the context that the question is asking. – VLAZ Dec 12 '21 at 14:15
  • @VLAZ is right, that's why I wrote "in your situation" – wolfenblut Jan 01 '22 at 13:01
0

JSON

In JSON format, keys have to be surrounded by quotes.

JSON Example:

{
    "name": "John",
    "age": 30
}

JSON5

JSON5 is a superset of JSON that adds some extra features to the original JSON format, including the ability to use single quotes or unquoted keys.

JSON5 Example:

{
    // This is a comment
    name: 'John',
    'age': 30,
}

Hjson

Hjson also allows for keys to be unquoted, as long as they don't contain spaces or other special characters. Hjson is essentially a more relaxed and forgiving version of JSON/JSON5 that allows for more flexibility in the formatting and syntax of the data.

Hjson Example:

{
  // This is a comment
  name: John
  age: 30
  city: New York
  favorites: [
    pizza
    ice cream,
  ]
}
cwtuan
  • 1,718
  • 1
  • 18
  • 20
-4

Since you can put "parent.child" dotted notation and you don't have to put parent["child"] which is also valid and useful, I'd say both ways is technically acceptable. The parsers all should do both ways just fine. If your parser does not need quotes on keys then it's probably better not to put them (saves space). It makes sense to call them strings because that is what they are, and since the square brackets gives you the ability to use values for keys essentially it makes perfect sense not to. In Json you can put...

>var keyName = "someKey";
>var obj = {[keyName]:"someValue"};

>obj
Object {someKey: "someValue"}

just fine without issues, if you need a value for a key and none quoted won't work, so if it doesn't, you can't, so you won't so "you don't need quotes on keys". Even if it's right to say they are technically strings. Logic and usage argue otherwise. Nor does it officially output Object {"someKey": "someValue"} for obj in our example run from the console of any browser.

Master James
  • 1,691
  • 15
  • 19
  • 2
    Both the accepted answer and the RFC that defines JSON say that the quotes are required. – Keith Thompson Jan 31 '16 at 03:24
  • That is true, but it's worth noting it logically doesn't need to. I suppose a JavaScript Object Notation output from the all browser console's is wrong, and we should tell somebody to fix that. Maybe what a Browser console outputs for an object is not JSON, so maybe JSON as the spec defines is not needed nor implemented that way in most places. Anyway I just wanted to make the case, that looks at the facts in a different light. Really maybe the spec should be changed then, "Quoted Keys" is simply not needed anywhere that matters to me personally. (It's just not used that way in practice.) – Master James Jan 31 '16 at 08:32
  • 3
    You are mixing up three different things: JSON, JavaScript object literals, and browser developer tools console output. When you type your `obj` in the console, the browser displays some human-readable representation of the object. It may display it as an object literal (as it did in your example), or it may use some other representation, even an interactive one. JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON _always_ requires quotes around key names. – Michael Geary Aug 10 '16 at 07:35
  • 4
    As further examples, instead of typing `obj` in the console, try `JSON.stringify(obj)`. Now you will see a valid JSON representation of the object, complete with quoted key name. Conversely, to see if a string is valid JSON, try `JSON.parse(string)`. If the keys are not quoted, this will throw an exception. For example, `JSON.parse('{"a":"b"}')` will succeed, but `JSON.parse('{a:"b"}')` will fail. – Michael Geary Aug 10 '16 at 07:37
  • Regarding your note that quoted keys are not needed anywhere that matters to you personally, that is because _you are not using JSON_. You are using JavaScript object literals, which have their own syntax that is not the same as JSON syntax. – Michael Geary Aug 10 '16 at 07:41
  • 1
    OTOH, your use of `var obj = {[keyName]:"someValue"};` is very interesting! I didn't know you could do that in a JavaScript object literal. A bit of checking shows that this is something new in ES6 - you couldn't do it in ES5. – Michael Geary Aug 10 '16 at 07:51
  • I saw Crockford who invented JSON in some video say "we should take them out but it's too late, sorry". I just use JS for my data now so I took the ON out of JSON ! All I'm really saying is, "think again". The Spec is the spec (period) but's not the best spec. I'm bringing it into JS so I don't need to convert it anymore in some sense (it's parsed still yes), and then you can have it that way. No quotes on labels/keys because no more json. – Master James Nov 25 '17 at 11:45
  • Note: I'm using websockets so it does get stringified for transmission but I never see it that way. Yes it's ES6 so it's finally maturing to resolve what drove it the wrong way, so that's it the square brakcets on labels/keys sets you free. If you have a space in your label/key you still need quotes so moot point really. – Master James Nov 25 '17 at 11:47