views:

303

answers:

4

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. (So I'll do that too for now)

+3  A: 

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

string
    ""
    " chars "
+6  A: 

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
+4  A: 

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

Read the whole RFC here

PatrikAkerstrand
A: 

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