69

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

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

2
  • spaces aren't technically blank characters Commented Nov 11, 2010 at 1:18
  • 34
    technically your brain should have parsed "blank" as "whitespace" Commented Jun 27, 2012 at 5:34

2 Answers 2

82

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
         )
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. I had read the RFC but was unsure what kind of grammar denotation language this was -- specifically, what the * meant.
* = zero or more (from regular expression notation)
What about spaces embedded in numeric values: is {"a":12} equivalent to {"a":1 2} I interpret the definition "Insignificant whitespace is allowed before or after any of the six structural characters" to imply that whitespace is NOT allowed inside a numeric or date value
@aeropapa17 That’s correct, since neither 1 nor 2 is a JSON structural character.
The grammar notation used in the spec is Augmented BNF (Backus-Naur form), which is defined in rfc-editor.org/rfc/rfc4234. There's a link to it in the JSON RFC but it's easy to miss.
|
7

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: DataContractJsonSerializer doesn't work with formatted 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?

1 Comment

Danger, Will Robinson!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.