何时可以在JSON中省略引号? [英] When can quotes be omitted in JSON?

查看:172
本文介绍了何时可以在JSON中省略引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是JSON保留得最好的秘诀之一:什么时候可以准确地省略字符串周围的引号-到底应该使用什么引号(单引号或双引号)?

JSON标准非常清楚:使用双引号,并始终使用它们.但是似乎没有人遵循它,并且解析器似乎对此一般都没问题.

例如,JSON文档中的键通常似乎不需要引号. (我猜这是因为解析器可以假定键必须是字符串文字).但这是一个实际规则吗?还有其他这样的规则吗?它们是特定于解析器还是特定于语言的?

请注意,尽管问题是关于JSON的,但这包括以给定编程语言表达JSON对象的标准方法.如果一种语言(例如JavaScript)具有从JSON标准转移过来的官方规则,那么对它们进行定义将很有帮助.

解决方案

删除JSON对象键中的引号是Javascript语言(可能还有其他语言)的功能.例如,Python的字典语法与Javascript非常相似,不同之处在于键名 不能用引号引起来(尽管它们可以单引号,并且不必是字符串). /p>

可能与以下问题重复: JSON规范-密钥是否必须用引号引起来? 而这个:这有什么区别在带引号和不带引号的对象键之间?

哪一个都没有解决这个问题是否在Javascript规范中,还是大多数浏览器只允许这样做.我在ECMAScript官方规范中找到了这个:

第一个定义对象文字,其中PropertyNameAndValue可以是StringLiteral或IdentifierLiteral.第二个定义了一个没有引号的IdentifierLiteral.

因此,是的,Java语言中正式允许使用无引号的属性名称.

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.

解决方案

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.

这篇关于何时可以在JSON中省略引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆