Reading Escaped Characters in JSON

JSON string syntax uses escapes to represent characters whose literal use would interfere with the string grammar or is convenient to encode.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read a newline escape
  2. Test literal backslashes independently
  3. Count characters before and after decoding
  4. Avoid mixing representation layers in tests

Read a newline escape

The JSON source spelling "line\nnext" represents text containing a newline between the two words. A displayed representation may show the backslash even after parsing if it is rendering an escaped view. See display representations.

Test literal backslashes independently

Text containing a backslash followed by n needs a different encoded spelling from text containing a newline. A round-trip test with both values can detect a parser that unescapes one time too many.[1]

Count characters before and after decoding

A JSON string spelling "line1\nline2" contains a backslash and n in the source escape. Decoding yields an actual line break between the words. A JSON spelling "line1\\nline2" instead produces a backslash followed by n in the decoded text. See escaping versus character encoding.

Source has \n  → decoded U+000A
Source has \\n → decoded backslash and letter n
Re-encode the decoded value with a JSON serializer

Avoid mixing representation layers in tests

A programming language string literal can process escapes before the JSON reader sees them. When testing, inspect the actual bytes or use a raw string where appropriate. Include a quote, a backslash and a newline.

References

  1. IETF, RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format ↩