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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With