Skip to content

ligumas/json.hpp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

json.hpp

single-header JSON parser for C++17

C++17 header-only license

drop json.hpp into your project. parse JSON. done.

#include "json.hpp"

auto v = json::parse(R"({
    "name": "jasper",
    "age": 20,
    "tags": ["cpp", "linux"]
})");

std::string name = v["name"].as_string();    // "jasper"
int age          = v["age"].as_int();         // 20
std::string tag  = v["tags"][0].as_string();  // "cpp"

install

copy json.hpp to your project.

API

json::Value v = json::parse(str);   // throws json::ParseError on bad input

v.is_null() / is_bool() / is_number() / is_string() / is_array() / is_object()

v.as_bool() / as_number() / as_int() / as_string()
v["key"]        // object access
v[0]            // array access
v.size()
v.contains("key")

std::string s = json::dump(v);       // pretty-printed, 2 space indent
std::string s = json::dump(v, 0);    // compact

building values manually:

json::Value obj = json::Object{};
obj.as_object()["x"] = json::Value(42);

json::Value arr = json::Array{ json::Value(1), json::Value(2) };

errors include line and column:

try {
    auto v = json::parse("{ bad }");
} catch (const json::ParseError& e) {
    std::cerr << e.what();  // "unexpected character 'b' (line 1, col 3)"
}

handles objects, arrays, strings, numbers (int/float), bools, null, and escape sequences including \uXXXX (decoded to UTF-8, surrogate pairs supported).

License: MIT

About

single-header JSON parser for C++17

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages