Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can quotes be omitted in JSON?

Tags:

json

It seems one of the best-kept secrets of JSON: When exactly can you leave out the quotes around a string – and what quotes (single or double) are you supposed to use anyway?

The JSON standard is pretty clear about it: use double quotes, and use them always. Yet nobody seems to follow that, and parsers seem generally fine with it.

For example, the keys in JSON documents generally don't seem to need quotes. (I guess that's because the parser can assume that the key must be a string literal). But is that an actual rule? Are there any other such rules? Are they parser-specific or language-specific?

Note that although the question is about JSON, this includes the standard way to express JSON objects in a given programming language. If a language (such as JavaScript) has official rules that divert from the JSON standard, it would be helpful to see them defined.

like image 974
drmirror Avatar asked Jan 12 '23 22:01

drmirror


2 Answers

Never. Dropping the quotes is legal in literals in JavaScript code, but illegal in JSON. Strings are always quoted, and keys are always strings. "Lax JSON" parsers may exist that accept illegal JSON with unquoted keys or other things, but that doesn't change the fact that it is illegal JSON as such, and no JSON parser is required to accept it.

like image 145
hobbs Avatar answered Jan 18 '23 04:01

hobbs


Dropping the quotes in JSON object keys is a feature of the Javascript language, and possibly others. Python, for instance, has a dictionary syntax that is pretty similar to Javascript except that key names cannot be unquoted (though they can be single-quoted, and they don't need to be strings).

May be a duplicate of this question: JSON Spec - does the key have to be surrounded with quotes? And this one: What is the difference between object keys with quotes and without quotes?

Neither of which addresses the question of whether this is in the Javascript specification, or if it is just allowed by most browsers. I found this in the official ECMAScript specification:

  • http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
  • http://www.ecma-international.org/ecma-262/5.1/#sec-7.6

The first defines an object literal, in which the PropertyNameAndValue can be a StringLiteral or an IdentifierLiteral. The second defines an IdentifierLiteral, which does not have quotes.

So, yes, unquoted property names are officially allowed in Javascript.

like image 27
Jim Pivarski Avatar answered Jan 18 '23 03:01

Jim Pivarski