When can quotes be omitted in JSON?

前端 未结 2 671
执念已碎
执念已碎 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.

提交回复
热议问题