An open API service indexing awesome lists of open source software.

https://github.com/defini7/json

Single header-file Json library
https://github.com/defini7/json

Last synced: about 1 month ago
JSON representation

Single header-file Json library

Awesome Lists containing this project

README

          

# Simple C++ JSON Parser

A lightweight, header-only JSON parser and serializer written in C++20.

## Features:
- Header-only library
- Supports objects, arrays, strings, numbers, booleans, null
- Pretty-printed JSON output
- Parse from strings or files

## Installation:

In ONE translation unit:
```cpp
#define JSON_IMPL
#include "json.hpp"
```

In other files:
```cpp
#include "json.hpp"
```

## Basic Usage:

### Parse from raw string:
```cpp
#include "json.hpp"

int main()
{
std::string raw = R"({
"name": "John",
"age": 30,
"active": true
})";

Json::Node root = Json::ParseRaw(raw);

std::cout << root["name"].String() << std::endl;
std::cout << root["age"].Number() << std::endl;
}
```

### Parse from file:
```cpp
auto result = Json::ParseFile("data.json");

if (result)
{
std::cout << result->operator[]("name").String() << std::endl;
}
```

### Accessing Values:

Objects:
```cpp
std::string name = root["name"].String();
double age = root["age"].Number();
bool active = root["active"].Bool();
```

Arrays:
```cpp
Json::Node& arr = root["items"];
std::cout << arr[0].String() << std::endl;
std::cout << arr[1].Number() << std::endl;
```

### Dumping JSON:

Print:
```cpp
root.Dump();
```

To string:
```cpp
std::string pretty = Json::Dump(root);
std::cout << pretty;
```

Custom indentation:
```cpp
std::string pretty = Json::Dump(root, 2);
```

### Supported Types:
- string -> String()
- number -> Number()
- boolean -> Bool()
- null -> IsNull()
- array -> Array()
- object -> Object()

### Type Checking:
```cpp
node.IsObject()
node.IsArray()
node.IsString()
node.IsNumber()
node.IsBool()
node.IsNull()
```

## Notes:
- Keys preserve insertion order
- Numbers are stored as double
- No escape sequence handling yet
- No unicode support
- Minimal error recovery

## License:
BSD 3-Clause License