When can quotes be excluded in JSON?

This seems to be one of JSON's best secrets: when can you leave quotes around the string - and what quotes (one or two) should you use anyway?

the JSON standard is pretty straightforward: use double quotes and always use them. However, no one is following this, and the parsers seem generally beautiful.

For example, keys in JSON documents usually do not need quotes. (I assume that since the parser might suggest that the key should be a string literal). But is this a rule? Are there any other 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 (like JavaScript) has official rules that are distracted from the JSON standard, it would be useful to see them defined.

+4
source share
2 answers

Removing quotes in JSON object keys is a feature of Javascript and possibly others. For example, Python has a dictionary syntax that is very similar to Javascript, except that key names cannot be unquoted (although they can be one-time, and they don't have to be strings).

There may be a duplicate of this question: JSON Spec - should the key be surrounded by quotation marks? And this one: What is the difference between object keys with quotes and without quotes?

None of them address the question of whether this is part of the Javascript specification or is simply allowed by most browsers. I found this in the official ECMAScript specification:

The first defines an object literal in which PropertyNameAndValue can be StringLiteral or IdentifierLiteral. The second defines an IdentifierLiteral that does not have quotation marks.

So yes, names without quotes are officially resolved in Javascript.

+3
source

Never. Removing quotes is legal in literals in JavaScript code, but illegal in JSON. Lines are always quoted, and keys are always strings. There may be Lax JSON parsers that accept illegal JSON with unspecified keys or other things, but this does not change the fact that it is illegal JSON as such and does not require a JSON parser to accept it.

+5
source

Source: https://habr.com/ru/post/1491330/


All Articles