build-a-json-parser / lesson-07.md
Lesson 07 · Scanning strings and numbers

The simple string escapes

A string cannot hold a raw quote or newline, so JSON spells those with backslash escapes. Today you decode the eight single-character escapes into the bytes they stand for.

The goal

Decode the eight backslash escapes into their literal characters inside a scanned string.

Start here - the target
TO DO
Scenario: Decoding backslash escapes
Givena quoted string containing backslash escapes
Whenit is scanned
Thenthe string written as quote, a, backslash, t, b, quote decodes to a, then a tab, then b
Andbackslash-quote decodes to a double quote, backslash-backslash to a single backslash, and backslash-n to a line feed
Background

Some characters cannot appear literally between quotes: a raw double quote would end the string early, and control characters like a newline are not allowed inside one. JSON solves this with escape sequences - a backslash followed by one more character that names the byte to produce. There are eight of these single-character escapes: \", \\, \/, \b, \f, \n, \r, and \t.

The moment you have escapes, you can no longer just slice the input between the quotes - the decoded value differs from the raw bytes. So build the value into a buffer instead: copy ordinary characters straight across, and when you hit a backslash, look at the next byte and append the single character it stands for. \b is backspace (byte 0x08) and \f is form feed (byte 0x0C); the rest map to the obvious ASCII characters. Unknown escapes and the \u form come in later lessons.

Make it work
// inside the string loop, when you see '\\', read the next byte:
// '"' -> '"' '\\' -> '\\' '/' -> '/'
// 'b' -> 0x08 'f' -> 0x0C 'n' -> '\n'
// 'r' -> '\r' 't' -> '\t'
// append the decoded byte to a build buffer, not the raw two bytes
CheckpointDONE
Strings with the eight simple escapes decode correctly. Commit and stop here.