Writing a tiny JSON Parser

JSON is one of the foundational data formats, especially with modern REST APIs, but many existing libraries are either large or small and hard to comprehend. In this blog post, I’ll show you how to implement a tiny JSON parser that follows the official JSON grammar directly. This parser will not be the fastest or the most featureful, but it will be good enough for many use cases, where you need to parse simple JSON structures returned by a REST API. The resulting library is femtojson.

TLDR: I built femtojson, a tiny JSON library.

Usage

This library is as minimal as possible, only emitting existing List, Map, and primitive types, instead of custom wrapper classes:

import me.bechberger.util.json.JSONParser;
import java.io.IOException;
import java.util.Map;
import java.util.List;

public class Example {
    public static void main(String[] args) throws IOException {
        // Parse a simple object
        String jsonObject = "{\"name\": \"Alice\", \"age\": 30}";
        Map<String, Object> obj = (Map<String, Object>) JSONParser.parse(jsonObject);
        
        System.out.println(obj.get("name"));  // Output: Alice
        System.out.println(obj.get("age"));   // Output: 30
        
        // Parse an array
        String jsonArray = "[1, 2, 3, 4, 5]";
        List<Object> numbers = (List<Object>) JSONParser.parse(jsonArray);
        
        System.out.println(numbers.get(0)); // Output: 1
        
        // Parse nested structures
        String complexJson = "{\"items\": [1, \"two\", 3.14], \"active\": true}";
        Map<String, Object> complex = (Map<String, Object>) JSONParser.parse(complexJson);
        
        List<Object> items = (List<Object>) complex.get("items");
        System.out.println(items.get(1)); // Output: two
        
        Boolean active = (Boolean) complex.get("active");
        System.out.println(active); // Output: true
    }
}

The library also contains a pretty printer and tests to check that all edge cases are handled properly.

We start this blog post by looking at the grammar:

Continue reading