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
---. 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
Complete source code
Makefile
What each file does
- src/json.h
- The
Valuetype,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:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
{
"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.txtwithtests/expected-output.txt. caf\u00e9becomes café and the surrogate pair 🚀 becomes 🚀 in the output (UTF-8).1.5e3prints 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
- 1Add a diff command that compares two documents.
- 2Validate a document against a tiny schema (required keys and types).
- 3Support comments and trailing commas as an opt-in 'JSON5-lite' mode.
Built and tested it yourself? Mark it to update your dashboard.