JSON 中的空白字符是否无关紧要?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4150621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are whitespace characters insignificant in JSON?
提问by user496949
Are blank characters like spaces, tabs and carriage returns ignored in json strings?
json 字符串中是否会忽略空格、制表符和回车等空白字符?
For example, is {"a":"b"}equal to {"a" : "b"}?
例如,{"a":"b"}等于{"a" : "b"}?
回答by Greg Hewgill
Yes, blanks outside a double-quoted string literal are ignored in the syntax. Specifically, the wsproduction in the JSON grammar in RFC 4627shows:
是的,语法中会忽略双引号字符串文字之外的空格。具体来说,RFC 4627中wsJSON 语法的产生式显示:
Insignificant whitespace is allowed before or after any of the six structural characters. ws = *( %x20 / ; Space %x09 / ; Horizontal tab %x0A / ; Line feed or New line %x0D ; Carriage return )
Insignificant whitespace is allowed before or after any of the six structural characters. ws = *( %x20 / ; Space %x09 / ; Horizontal tab %x0A / ; Line feed or New line %x0D ; Carriage return )
回答by Tim Goodman
In standard JSON, whitespace outside of string literals is ignored, as has been said.
如前所述,在标准 JSON 中,字符串文字之外的空格被忽略。
However, since your question is tagged C#, I should note that there's at least one other case in C#/.NET where whitespace in JSON does matter.
但是,由于您的问题被标记为 C#,我应该注意到,在 C#/.NET 中至少还有另一种情况,其中 JSON 中的空格很重要。
The DataContractJsonSerializeruses a special __typeproperty to support deserializing to the correct subclass. This property is required to be the first property in an object, and to have no whitespace between the property name and the preceeding {. See this previous thread:
DataContractJsonSerializer doesn't work with formatted JSON?
在DataContractJsonSerializer使用一种特殊的__type属性,以支持反序列化到正确的子类。此属性必须是对象中的第一个属性,并且属性名称和前面的{. 请参阅上一个主题:
DataContractJsonSerializer 不适用于格式化的 JSON?
At least, I have tested that the no-whitespace requirement is true as of .NET 4. Perhaps this will be changed in a future version to bring it more into line with the JSON standard?
至少,我已经测试过,从 .NET 4 开始,无空格要求是正确的。也许在未来的版本中会改变这一点,使其更符合 JSON 标准?

