HTTP API: Explicit Contracts · 25 min · free lesson

Encode a Valid JSON Boundary

Escape JSON strings without corrupting Unicode.

Core idea

Escape control characters, quotes and backslashes while preserving Unicode data.

Diagram for Encode a Valid JSON Boundary: a Rust code example flows to the lesson rule and the key observation.
The worked implementation exercises escape json strings without corrupting unicode. Its tests demonstrate the stated finite contract.

Understand it

JSON is a wire format, not arbitrary quoted text. A title containing a quote or newline must remain one string value. Direct interpolation can terminate a string or create a response that no client can decode. Escape the JSON control set while retaining the original Unicode scalar values.

The exercise builds one JSON string value, including its surrounding quotes. It is deliberately small enough to inspect; the desktop service should use Serde instead of maintaining a general JSON implementation. Do not treat this function as a parser, canonical JSON signer or complete serializer. HTTP response byte lengths must be computed from encoded UTF-8 bytes after serialization, not from character count. The local adapter recalculates Content-Length and closes each connection so an edited response cannot smuggle a second framed response.

The route project is Task Ledger: first keep a reproducible source history, then expose its data through a CLI and HTTP boundary, persist it in SQL, diagnose failures and prepare a release. This lesson owns one contract in that project. Run the worked example before changing the starter and explain which input makes the tempting shortcut fail.

Terminal practice: Inspect curl -i output for a title containing quotes. Compare the response Content-Length with its encoded body.

The compiler lab is independent of the reading question. Edit solution.rs; the app supplies a separate caller with normal, empty and adversarial inputs. A successful unchanged demonstration does not prove your implementation. After the lab, apply the same contract to the route companion project. Its README separates the on-device adapter from the desktop Cargo/TCP profile.

Read the code

pub fn json_string(value: &str) -> String {
    let mut out = String::from("\"");
    for c in value.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c < ' ' => {
                out.push_str(&format!("\\u{:04x}", c as u32))
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

fn main() {
    assert_eq!(json_string("hi"), "\"hi\"", "case 1");
    assert_eq!(json_string(""), "\"\"", "case 2");
    assert_eq!(json_string("a\"b"), "\"a\\\"b\"", "case 3");
    assert_eq!(
        json_string(
            "a
b"
        ),
        "\"a\\nb\"",
        "case 4"
    );
    assert_eq!(json_string("🦀"), "\"🦀\"", "case 5");
    println!("worked example passed");
}

The worked implementation exercises escape json strings without corrupting unicode. Its tests demonstrate the stated finite contract.

Practice starter

pub fn json_string(value: &str) -> String {
    todo!("implement the contract")
}

Open local example in Playground ↗

Try it

Return a quoted JSON string; escape quote, backslash, newline, carriage return and tab, encode remaining controls below U+0020 as lowercase four-digit \u escapes, and retain other Unicode scalars. Keep the public signature. Open the compiler lab and edit solution.rs; do not edit the private verification caller.

What success looks like: The separate caller accepts the changed solution and rejects unchanged TODO, a wrong implementation and a printed success message.

Check your understanding

Which response length belongs in Content-Length?

Reveal the answer
  1. The serialized body byte length
  2. The number of Rust char values
  3. The unescaped input title length

Escaping and UTF-8 encoding can both change byte length.

Go deeper

Common misconception: The number of Rust char values

Escape control characters, quotes and backslashes while preserving Unicode data.

  1. Identify the boundary: Escape JSON strings without corrupting Unicode. Write down its accepted inputs and observable output.
  2. Exercise the failure: Escaping and UTF-8 encoding can both change byte length.
  3. Check the independent caller: Return a quoted JSON string; escape quote, backslash, newline, carriage return and tab, encode remaining controls below U+0020 as lowercase four-digit \u escapes, and retain other Unicode scalars.

Transfer challenge: Apply this contract to Task Ledger, introduce the failure described in the lesson, and show the failing check before fixing it.

Connections

  • Validate Before Applying Effects: Check declared and actual request size
  • Retry Without Duplicating Tasks: Bind an idempotency key to one request payload