Capstone 1: writing JSON

The model of lesson 129 describes a JSON value; this lesson turns one into text. The writer is a switch over the same six forms, a StringBuilder that grows as it goes, and two rules that a naive writer gets wrong: the escaping inside a string and the form of a number.

render

The entry point takes a value and answers its text. The recursive part takes the builder and a flag for the pretty form, because the two forms share every rule except the spacing, and a second copy of the six cases would be a second place to fix a bug:

import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class JsonWriter { sealed interface Json permits JNull, JNumber, JString, JBool, JArray, JObject { } record JNull() implements Json { } record JNumber(double value) implements Json { } record JString(String value) implements Json { } record JBool(boolean value) implements Json { } record JArray(List<Json> values) implements Json { } record JObject(Map<String, Json> fields) implements Json { } static final String BACKSLASH = String.valueOf((char) 92); static final String QUOTE = String.valueOf((char) 34); static String render(Json json) { StringBuilder out = new StringBuilder(); write(json, out, 0, false); return out.toString(); } static void write(Json json, StringBuilder out, int indent, boolean pretty) { switch (json) { case JNull() -> out.append("null"); case JNumber(double value) -> out.append(number(value)); case JString(String value) -> quote(value, out); case JBool(boolean value) -> out.append(value); case JArray(List<Json> values) -> { out.append('['); for (int i = 0; i < values.size(); i++) { if (i > 0) { out.append(pretty ? ", " : ","); } write(values.get(i), out, indent + 1, pretty); } out.append(']'); } case JObject(Map<String, Json> fields) -> { out.append('{'); int i = 0; for (Map.Entry<String, Json> field : fields.entrySet()) { if (i++ > 0) { out.append(","); } if (pretty) { out.append('\n').append(" ".repeat(indent + 1)); } quote(field.getKey(), out); out.append(pretty ? ": " : ":"); write(field.getValue(), out, indent + 1, pretty); } if (pretty && !fields.isEmpty()) { out.append('\n').append(" ".repeat(indent)); } out.append('}'); } } } static String number(double value) { return value == Math.rint(value) && !Double.isInfinite(value) ? Long.toString((long) value) : Double.toString(value); } static void quote(String text, StringBuilder out) { out.append(QUOTE); for (char c : text.toCharArray()) { if (c == 34) { out.append(BACKSLASH).append(QUOTE); } else if (c == 92) { out.append(BACKSLASH).append(BACKSLASH); } else if (c == 10) { out.append(BACKSLASH).append('n'); } else if (c == 9) { out.append(BACKSLASH).append('t'); } else if (c < 32) { out.append(BACKSLASH).append('u').append(String.format("%04x", (int) c)); } else { out.append(c); } } out.append(QUOTE); } static String pretty(Json json) { StringBuilder out = new StringBuilder(); write(json, out, 0, true); return out.toString(); } public static void main(String[] args) { Map<String, Json> fields = new LinkedHashMap<>(); fields.put("name", new JString("Ada")); fields.put("age", new JNumber(36)); fields.put("admin", new JBool(true)); fields.put("nickname", new JNull()); fields.put("tags", new JArray(List.of(new JString("math"), new JString("code")))); Json user = new JObject(fields); String tricky = "say " + QUOTE + "hi" + QUOTE + (char) 9 + "and " + BACKSLASH + " done"; System.out.println(render(user)); System.out.println(pretty(user)); System.out.println(render(new JString(tricky))); System.out.println(render(new JNumber(12.5))); System.out.println(render(new JArray(List.of()))); } }

javac -Xlint:all JsonWriter.java
java JsonWriter

{"name":"Ada","age":36,"admin":true,"nickname":null,"tags":["math","code"]}
{
  "name": "Ada",
  "age": 36,
  "admin": true,
  "nickname": null,
  "tags": ["math", "code"]
}
"say \"hi\"\tand \\ done"
12.5
[]

Escaping a string

A JSON string is inside double quotes, so a quote in the value has to be escaped, and so does the backslash that starts an escape. The writer turns those two into \" and \, a newline into \n, a tab into \t, and any other control character into the six-character form \u0001.

The fourth line of the output is the proof: the value is say "hi", a tab, and, a backslash and done, and the text shows the escapes instead of the characters. The two characters are built as String.valueOf((char) 92) and String.valueOf((char) 34) so that the source of this page can be copied out of the HTML without its own escaping in the way; a program of your own writes them as the literals \" and \ and means the same thing. A writer that forgot the backslash would produce a document that a reader parses differently, which is the kind of bug that shows up only on the input that contains the character.

Writing a number

A double of 36 prints as 36.0, and JSON allows that. The writer prints 36 because the number has no fraction, and keeps 12.5 as it is. The test is value == Math.rint(value), which asks whether the value is a whole number, and the cast to long is safe under that test for every value a JSON document holds.

The infinite and the NaN values are the case to think about, because JSON has no form for them. The writer leaves them as Infinity and NaN, which no parser accepts; a stricter writer throws instead. The tests of lesson 135 check the numbers that do occur, and the prose of the page says what the code does not do.

The pretty form

The second line of the output is the same document with a newline after the opening brace, two spaces of indentation per level, and a space after each colon. The flag is one boolean through the recursion, and the indentation is " ".repeat(indent + 1), because the depth is what the recursion already knows.

The array is not broken across lines in the pretty form, and that is a choice: a short array of scalars reads better on one line, and an array of objects would want its own rule. A writer that made every decision would be a library; this one has the two forms the project needs.

The output checked

Read the first line against the model of lesson 129: five fields, in the order they were put in, with the array of two strings inside the last one. The types are all there: a string in quotes, a number without one, true as a bare word, null as a bare word, an array in brackets and an object in braces.

The empty array prints as [] and would print as {} for an empty object; both are valid JSON, and a reader distinguishes them by the bracket. The writer has no other state, so the same value always gives the same text, which is what a test can compare against a string.

Exercises

  1. Add a control character to the demo string and check the six-character escape.
  2. Make the pretty form break long arrays across lines and run the program again.
  3. Write a compact method that is render without the flag, and explain why the two share the recursion.
  4. Throw for an infinite or NaN number and add the case to the prose of the page.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why does the writer append to a StringBuilder?

    Answer

    A loop of concatenations copies the whole text on every pass

    The builder keeps one buffer, which is the lesson of lesson 025 applied to a tree.

  2. Which characters must be escaped inside a JSON string?

    Answer

    The quote, the backslash and the control characters

    The quote and the backslash would end or change the string, and a control character has no literal form.

  3. Why does 36 print as 36 and not 36.0?

    Answer

    The writer prints a whole number without a fraction

    Both are valid JSON, and the shorter form is the one a reader expects.

  4. What does this program print? public class Q1 { public static void main(String[] args) { String text = "a\"b"; StringBuilder out = new StringBuilder(); out.append(34); text.chars().forEach(c -> { }); System.out.println(text.length()); System.out.println(text); } }

    Answer

    3 / a"b

    The value has three characters, and printing it shows the quote as it is.

  5. Where does the writer put the escaped characters?

    Answer

    Inside the quotes of a string, in the value and in the key

    A key is a string too, and it goes through the same quote method.

  6. Why is the pretty form the same recursion with a flag?

    Answer

    The rules of the two forms differ only in the spacing, so a second copy would be a second bug

    One switch with one boolean keeps the shape and the escapes in a single place.

  7. What does an empty array print as?

    Answer

    []

    The brackets are the form, and an empty object would print as two braces.

  8. What does this program print? public class Q2 { public static void main(String[] args) { String backslash = String.valueOf((char) 92); StringBuilder out = new StringBuilder(); out.append(backslash).append(backslash); System.out.println(out.length()); System.out.println(out); } }

    Answer

    2 / \\

    Two backslash characters are appended, and the line shows both of them.

  9. Why does a control character need the six-character form?

    Answer

    It has no literal form in a JSON string

    JSON names it as \u followed by four hexadecimal digits.

  10. What does Math.rint answer?

    Answer

    The nearest whole number, as a double

    Comparing the value with it asks whether the number has no fraction.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev