Do the JSON keys have to be surrounded by quotes?

Viewed 103474

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.

7 Answers

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"}.

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.

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)

Yes they do. But if you need otherwise, checkout JSON5.

JSON5 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.

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?

Related