Escaping and Character Encoding

Escaping follows a textual grammar to distinguish special data. Character encoding maps the resulting text into bytes.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace the two stages
  2. Find which stage failed
  3. Trace two transformations in the correct order
  4. Check what each transformation can fix

Trace the two stages

A JSON string containing a quotation mark uses an escape in its JSON spelling. That surrounding spelling can then be encoded as UTF-8 for transfer. JSON string escapes govern the first step and text encoding governs the second.

Find which stage failed

A byte sequence may decode cleanly to UTF-8 and still be invalid JSON if a string is unterminated. Give each stage its own diagnostic so a caller knows what needs correction.[1][2]

Trace two transformations in the correct order

To send text containing a newline in a JSON string, a JSON serializer escapes the newline on its syntax layer. A UTF-8 encoder then converts the serialized JSON characters to bytes. Decoding runs in reverse order. See JSON string escapes.

Value: A, logical newline, B
JSON string text: "A\nB"
UTF-8 bytes of JSON text: 22 41 5C 6E 42 22
Parsing after decoding restores the newline

Check what each transformation can fix

Escaping quotes helps preserve a string's syntax boundaries. It cannot turn invalid UTF-8 into valid source text. Choosing UTF-8 preserves supported characters as bytes, and JSON syntax still needs quote and escape rules.

References

  1. IETF, RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format ↩
  2. IETF, RFC 3629: UTF-8, a Transformation Format of ISO 10646 ↩