Are whitespace characters insignificant in JSON?

Json

Json Problem Overview


Are blank characters like spaces, tabs and carriage returns ignored in json strings?

For example, is {"a":"b"} equal to {"a" : "b"}?

Json Solutions


Solution 1 - Json

Yes, blanks outside a double-quoted string literal are ignored in the syntax. Specifically, the ws production in the JSON grammar in RFC 4627 shows:

> 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 > )

Solution 2 - Json

In standard JSON, whitespace outside of string literals is ignored, as has been said.

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.

The DataContractJsonSerializer uses a special __type property 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: https://stackoverflow.com/questions/5824696/datacontractjsonserializer-doesnt-work-with-formatted-json/15445023?noredirect=1#comment23901691_15445023

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?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser496949View Question on Stackoverflow
Solution 1 - JsonGreg HewgillView Answer on Stackoverflow
Solution 2 - JsonTim GoodmanView Answer on Stackoverflow