A lightweight JSON parser and serializer for C++17. This library allows you to parse JSON strings, manipulate JSON objects and arrays, and serialize them back to JSON format. It includes robust error handling, support for nested structures, and a simple API for easy use.
json-parse/
├── example/ # Example programs demonstrating usage
│ ├── json.cpp
│ ├── parse.cpp
│ └── stringify.cpp
├── src/ # Source headers
│ ├── JSON.h
│ ├── JSONNode.h
│ ├── Parser.h
│ ├── Serializer.h
│ └── Utils.h
├── tests/ # Unit tests
│ ├── official_test.cpp
│ ├── test_json.cpp
│ ├── test_parser.cpp
│ └── test_stringify.cpp
├── Makefile # Build system
├── json-parser.cpp # Main executable
├── notes.md # Notes and documentation
└── README.md # This file
- Parse JSON strings into C++ objects (
JSON/JSONNode) - Manipulate objects, arrays, and primitive types (
int,double,bool,string) - Serialize JSONNode objects back into JSON strings
- Supports nested objects and arrays
- Handles
null,true,false, numbers, strings, arrays, and objects - Robust error handling for malformed JSON
- Simple API inspired by JavaScript object access
Clone the repository:
git clone https://github.com/sakkshm/json-parse.git
cd json-parseBuild the project (requires C++17):
makeThis will compile all tests and the main binary in bin/.
./bin/json-parser <path/to/file.json>#include "src/JSON.h"
#include <iostream>
int main() {
std::string jsonStr = R"({"name":"Saksham","age":20,"skills":["C++","Python"]})";
JSONNode person = parse(jsonStr);
std::cout << "Name: " << person["name"].asString() << "\n";
std::cout << "Age: " << person["age"].asInt() << "\n";
std::cout << "First skill: " << person["skills"][0].asString() << "\n";
return 0;
}JSON person;
person["name"] = "Saksham";
person["age"] = 20;
person["skills"] = std::vector<JSONNode>{"C++", "Python", "TS"};
std::cout << stringify(person) << std::endl;
// Output: {"name":"Saksham","age":20,"skills":["C++","Python","TS"]}Run all tests:
make testThis will execute all binaries in bin/ prefixed with test_ and stop on the first failure.
- Constructors:
JSONNode(),JSONNode(int),JSONNode(double),JSONNode(const std::string&),JSONNode(bool),JSONNode(std::vector<JSONNode>) - Type checks:
isObject(),isArray(),isValue(),isNull() - Accessors:
operator[](std::string key),operator[](int index) - Value getters:
asInt(),asDouble(),asBool(),asString(),asArray() - Helpers:
keys(),contains(key),size(),empty()
JSONNode parse(const std::string &jsonStr)→ Parse JSON stringstd::string stringify(const JSONNode &node)→ Serialize JSONNode to string
- Maximum nesting depth: 32 levels (
MAX_DEPTH) - Trailing commas are not allowed in objects or arrays
- Robust against malformed JSON (throws
std::runtime_error)
See example/ for:
json.cpp→ Building JSON objects programmaticallyparse.cpp→ Parsing JSON stringsstringify.cpp→ Serializing JSON objects