Skip to content
C++ project #22Advanced

JSON Parser and Query Tool

A strict JSON parser built on std::variant: full string escapes and Unicode, precise error positions, pretty and compact printing, statistics and path queries.

Estimated time
~10 hours to build
Files
7 files · 679 lines
Technologies
C++17, <variant>, <memory>, <map>, Header/source split

Introduction

JSON is the lingua franca of APIs, and writing a parser for it touches almost every modern C++ feature: std::variant for a value that can be one of six types, recursion for nested structures, std::visit with if constexpr for printing, and careful character handling for escapes and UTF-8.

Problem statement

Read one or more JSON documents separated by ---. For each, either report the first error with line and column (unterminated strings, trailing commas, duplicate keys, leading zeros, invalid escapes, excessive nesting), or print its type and statistics, a compact and a pretty-printed form, and answer path queries such as students[1].name.

Objectives

  • Model a recursive sum type with std::variant and shared_ptr
  • Write a strict recursive-descent parser following the JSON grammar
  • Use std::visit with a generic lambda and if constexpr
  • Encode Unicode code points (including surrogate pairs) as UTF-8

Features

  • Strict RFC 8259 parsing with positions in error messages
  • \uXXXX escapes and surrogate pairs
  • Compact and indented output with stable key order
  • Path queries and document statistics
  • Nesting limit to protect the stack

Concepts demonstrated

  • Sum types
  • Recursive-descent parsing
  • std::visit
  • if constexpr
  • UTF-8 encoding
  • Error reporting

System architecture

json::Value wraps std::variant<nullptr_t, bool, double, string, shared_ptr<Array>, shared_ptr<Object>>; the containers are behind pointers because a type cannot directly contain itself. The Parser class keeps an index into the text and has one method per grammar rule; fail computes the line and column from the index and throws ParseError. dump uses std::visit with a generic lambda and if constexpr branches per type. query walks a path of .key and [index] steps and returns nullptr when any step is missing.

Folder structure

TextProject tree
json-parser/
├── README.md
├── Makefile
├── src/json.cpp
├── src/json.h
├── src/main.cpp
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/json.h
The Value type, ParseError, and the parse / dump / query / analyse interface.
src/json.cpp
The strict parser (objects, arrays, strings with escapes, numbers), the printer and path queries.
src/main.cpp
Splits the input into documents and queries and prints the results.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Document 1 ===
Valid JSON (object): 4 objects, 4 arrays, 9 strings, 8 numbers, 1 booleans, 1 nulls; depth 4
Compact: {"course":"C++ Programming","meta":{"notes":"line1\nline2","size_kb":1500,"version":2},"published":true,"rating":4.75,"students":[{"marks":[92,88,95],"mentor":null,"name":"Asha"},{"marks":[67,74],"mentor":"Meera","name":"Ravi \"RK\" Kumar"}],"tags":["oop","stl","café","🚀"]}
Pretty:
{
"course": "C++ Programming",
"meta": {
"notes": "line1\nline2",
"size_kb": 1500,
"version": 2
},
"published": true,
"rating": 4.75,
"students": [
{
"marks": [
92,
88,
95
],
"mentor": null,
"name": "Asha"
},
{
"marks": [
67,
74
],
"mentor": "Meera",
"name": "Ravi \"RK\" Kumar"
}
],
"tags": [
"oop",
"stl",
"café",
"🚀"
]
}
? course => "C++ Programming" (string)
? students[1].name => "Ravi \"RK\" Kumar" (string)
? students[0].marks[2] => 95 (number)
? students[5] => not found
? meta.size_kb => 1500 (number)
? tags => ["oop","stl","café","🚀"] (array)
? meta.missing => not found
=== Document 2 ===
Valid JSON (array): 1 objects, 4 arrays, 0 strings, 4 numbers, 0 booleans, 0 nulls; depth 3
Compact: [1,2,[3,[4,[]]],{}]
Pretty:
[
1,
2,
[
3,
[
4,
[]
]
],
{}
]
=== Document 3 ===
Invalid JSON at line 1, column 13: duplicate key "a"
=== Document 4 ===
Invalid JSON at line 1, column 28: expected a string key
=== Document 5 ===
Invalid JSON at line 2, column 1: expected ',' or ']' in array
=== Document 6 ===
Invalid JSON at line 1, column 7: numbers cannot have leading zeros
=== Document 7 ===
Valid JSON (string): 0 objects, 0 arrays, 1 strings, 0 numbers, 0 booleans, 0 nulls; depth 0
Compact: "just a string"
Pretty:
"just a string"
? => "just a string" (string)
Input
{
  "course": "C++ Programming",
  "published": true,
  "rating": 4.75,
  "students": [
    {"name": "Asha", "marks": [92, 88, 95], "mentor": null},
    {"name": "Ravi \"RK\" Kumar", "marks": [67, 74], "mentor": "Meera"}
  ],
  "tags": ["oop", "stl", "café", "🚀"],
  "meta": {"version": 2, "size_kb": 1.5e3, "notes": "line1\nline2"}
}
? course
? students[1].name
? students[0].marks[2]
? students[5]
? meta.size_kb
? tags
? meta.missing
---
[1, 2, [3, [4, []]], {}]
---
{"a": 1, "a": 2}
---
{"name": "Asha", "age": 21,}
---
[1, 2
---
{"n": 012}
---
"just a string"
?
---

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt.
  • caf\u00e9 becomes café and the surrogate pair 🚀 becomes 🚀 in the output (UTF-8).
  • 1.5e3 prints as 1500; keys are printed in sorted order.
  • Errors: duplicate key at column 13, trailing comma, missing ] reported at line 2, and leading zero in 012.

Common errors

error: field has incomplete type 'Value'

A variant can't hold its own type directly; store arrays and objects behind std::shared_ptr (or std::unique_ptr with a custom copy).

Deeply nested input crashes the program

Recursive parsers use the call stack; limit the depth, as MAX_DEPTH does.

Possible improvements

  • Preserve the original key order
  • Add JSON Pointer (RFC 6901) queries
  • Stream large files instead of reading them whole

Additional challenges

  1. 1Add a diff command that compares two documents.
  2. 2Validate a document against a tiny schema (required keys and types).
  3. 3Support comments and trailing commas as an opt-in 'JSON5-lite' mode.

Built and tested it yourself? Mark it to update your dashboard.