When can quotes be omitted in JSON?

前端 未结 2 670
执念已碎
执念已碎 2021-01-20 00:49

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?

相关标签:
2条回答
  • 2021-01-20 01:12

    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.

    0 讨论(0)
  • 2021-01-20 01:14

    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.

    0 讨论(0)
提交回复
热议问题