A very sane (header only) C++14 JSON library

Overview

JeayeSON - a very sane C++14 JSON library Build Status

JeayeSON was designed out of frustration that there aren't many template-based approaches to handling JSON in modern C++. Given a very limited number of types (that JSON offers), functions can be written in a generic manner to provide the most consistent interface, no matter the type. JeayeSON is a non-validating JSON library; it expects valid JSON all of the time.

  • Header only (easy to add to any project)
  • Small, consistent C++ API
  • Typesafe, C++14 interface
  • Absolutely no macros needed nor used
  • UTF-8 (with UTF-16 transcoding)
  • Extensive test suite (using jest, a "sane and minimal C++14 unit test framework")

Practice

Assuming the JeayeSON headers are in your search path, simply

#include <jeayeson/jeayeson.hpp>

NOTE: If you're on Windows and symbolic links don't work, use

#include <jeayeson/value.hpp>

This will give you access to the following types:

json_value    /* variant type */
json_map      /* string->json_value map */
json_array    /* contiguous array of json_values */
json_null     /* json_value's default state */
json_int      /* defaults to int64_t */
json_float    /* defaults to double */
json_file     /* aggregate type representing a filename */
json_data     /* aggregate type representing json data as a string */

Building JSON

Assume we want to create this JSON:

{
  "hello": "world",
  "arr":
  [ 1.1, 2.2, 3.3 ],
  "person":
  {
    "name": "Tom",
    "age": 36,
    "weapon": null
  }
}

We can simply do:

json_value val // json_value can be any json type; here, it's a json_map
{
  { "hello", "world" }, // nested pairs represent key/value
  {
    "arr",
    { 1.1, 2.2, 3.3 } // arrays are easy
  },
  {
    "person",
    {
      { "name", "Tom" },
      { "age", 36 },
      { "weapon", nullptr } // can also use json_null
    }
  }
};

Or, if we wanted to build it piece by piece:

json_map val; // explicitly make a map this time

val["hello"] = "world"; // simple assignments work on all compatible types

val["arr"] = { 1.1, 2.2, 3.3 }; // implicit array construction

json_map person; // we'll build the person separately, too
person["name"] = "Tom";
person["age"] = 36;
person["weapon"] = nullptr;

val["person"] = person; // now we can just put the person map into val

// we can even dig into nested maps and arrays using op[]
val["person"]["name"] = "Susan";

Reading a JSON string

std::string json; // Acquired/initialized elsewhere
json_array arr{ json_data{ json } }; // simple aggregate for type-safety

Reading a file

json_map map{ json_file{ "my_file.json" } }; // simple aggregate for type-safety

Writing JSON

// maps, arrays, and values can all be used with streams
json_map map{ json_file{ "my_file.json" } };
std::cout << map << std::endl;

// you can also just write them to a string
std::string const json{ map.to_string() };

Feels like the C++ stdlib

You'll find all the normal stdlib-like functions, including iterator support.

json_array json;
json.push_back("string");
json.push_back(3.14159);
json.push_back(false);

for(auto const &j : json) // has begin, end, cbegin, cend, etc
{ std::cout << j << std::endl; }

// works like an std::vector or std::map
json.size();
json.empty();
json.clear();
json.reserve(42);

Type checking and casting

json_map json
{
  { "boolean", false },
  { "str", "..." }
};

// check types with is<T>()
json["boolean"].is<json_value::type::boolean>(); // true
json["str"].is<json_value::type::string>(); // true

// query the type enum
auto const type(json["str"].get_type());

// cast with as<T>() to get the complete type
auto const str(json["str"].as<json_string>());

Installation

The ./configure script must be used at least once to automagically generate jeayeson/config.hpp (see Customization). Since JeayeSON is a header-only library, simply copy over the contents of include to your project, or, better yet, add JeayeSON as a submodule and introduce jeayeson/include to your header search paths

A full installation can also be achieved by using ./configure && make install. See the ./configure script for prefix options.

Dependencies

  • A C++14 compiler (GCC 5.x or Clang 3.8+ recommended)
  • Boost (1.55.0+ recommended)

Customization

NOTE: All configuration is easily done in jeayeson/config.hpp, which is generated when you run ./configure (and is not overwritten subsequently -- delete it to reset).

Customization can be achieved by adjusting the types in the jeayeson::config struct template. A specialization is already provided, which contains the default types used by JeayeSON. Feel free to change the types to any other, still compatible, types.

For example, you may want the json integer type to be 32bit instead of the default 64bit. Or, you may want to use std::unordered_map instead of std::map.

Building tests

NOTE: You don't actually have to build JeayeSON, since it's a header-only library. This build process is only for the tests.

In the project directory, run:

$ ./configure && make

# Depending on your compiler setup (gcc or clang, linux or osx, etc)
# you may need to specify some extra flags. An example case:
# (allows clang & libc++ to work on Arch Linux)
$ CXX=clang++ CXX_FLAGS=-stdlib=libc++ LD_LIBS=-lc++abi make

Once built, you can run the tests:

$ make test

The tests (in test/src and test/include) can give more examples on how to use JeayeSON.

Comments
  • Current escaped strings are incomplete

    Current escaped strings are incomplete

    Currently we only escape character ", but with further thinking, we also need to escape all strings which start with \, e.g. \\, \n ..., in both reading and writing.

    bug 
    opened by xu-cheng 9
  • odr violation fixes

    odr violation fixes

    Added fixes for ODR violations (that resulted in linker errors) + minimalistic regression test.

    §14.7.3/12: An explicit specialization of a function template is inline only if it is declared with the inline specifier or defined as deleted, and independently of whether its function template is inline.

    I was not sure how you'd like to handle additional tests, so I've just added a simple cmake.

    opened by kuhar 4
  • json_map has method + tests

    json_map has method + tests

    I'd found using .find and then comparing the result to .end() too verbose, so I've added .has method to json_map that checks whether or not a map contains specific key. It comes in two flavors: templated on expected value type and not - just like .get.

    opened by kuhar 3
  • make of test project (and my project) fails with error on the overloaded <<

    make of test project (and my project) fails with error on the overloaded <<

    opened by yorkish 2
  • Don't escape '/' automatically

    Don't escape '/' automatically

    The JSON specification doesn't put '/' in the control character list (cf http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf p.4) : the characters that must be escaped range from U+0000 to U+001F according to the spec and '/' is U+002F; escaping is possible but not mandatory for '/'.

    Could it be possible to not automatically escape '/' ? When putting unix-y paths in json values, it's very cumbersome to read (\/usr\/local\/lib...).

    enhancement 
    opened by jcelerier 2
  • codecvt missing in libstdc++

    codecvt missing in libstdc++

    When compiling with gcc-4.9 and using libstdc++ following error occurs: `In file included from include/jeayeson/detail/parser_util.hpp:20: include/jeayeson/detail/utf.hpp:12:10: fatal error: 'codecvt' file not found

    include `

    How about using boost equivalent?

    opened by kuhar 2
  • No mention of Boost dependencies in README

    No mention of Boost dependencies in README

    There's no mention of the Boost dependencies anywhere in the project that I could find, except for the include directives that unfortunately brought my program to a halt when I tried to use jeayeson. While it would be great to not have these dependencies (feature request?), these should at least be prominently documented. A lot of users won't have or want to deal with Boost, and others will at least need to know how to install is required by this project.

    enhancement 
    opened by dfego 1
  • Fix incorrect prefix parameter

    Fix incorrect prefix parameter

    $PREFIX should be $prefix.

    Otherwise, configuring with a custom --prefix="" value fails.

    $ ./configure --prefix=/tmp/ROOT            
    Configuring jeayeson
    Platform: Linux
    ./configure: line 88: PREFIX: unbound variable
    
    opened by cengiz-io 1
  • JSON is always preparsed

    JSON is always preparsed

    Allow for the specification of when JSON is parsed (sync vs async 'lazy'). This would be nice as an added template param of json_map and json_array.

    json_map<json_parse::async> my_map; // maybe something like this? <-- Requires C++11 (how could it be done without it?)

    Perhaps json_map json_map_sync json_array json_array_sync (or similar?)

    Functions in json_map and json_array would then be specialized on those types. Meaning 4 new files (map_sync, map_async, array_sync, array_async). The problem with this is the duplication of code.

    Further note: How would json_map::size() or similar work on an async object?

    enhancement 
    opened by jeaye 1
  • `make install` does not copy `details` directory

    `make install` does not copy `details` directory

    Hi there,

    include/details directory is not copied to target installation directory.

    Thus, header resolving fails:

    $ clang++ -std=c++14  json_test.cpp -o json_test -IROOT/include/ 
    In file included from json_test.cpp:1:
    ROOT/include/jeayeson/jeayeson.hpp:14:10: fatal error: 'detail/traits.hpp' file not found
    #include "detail/traits.hpp"
            ^
    1 error generated.
    

    If I manually copy details directory under include/jeayeson, compilation succeeds.

    Have a nice day

    opened by cengiz-io 0
  • Formatting output?

    Formatting output?

    Hi,

    Is it possible to get a formatted output with some indentation? I've tried to dump a json file, but it gets dumped in a single line, which isn't readable.

    opened by lukkio88 1
Owner
Jeaye Wilkerson
I'm a leader, a problem solver, and a hacker with a passion for privacy and security.
Jeaye Wilkerson
https://github.com/json-c/json-c is the official code repository for json-c. See the wiki for release tarballs for download. API docs at http://json-c.github.io/json-c/

\mainpage json-c Overview and Build Status Building on Unix Prerequisites Build commands CMake options Testing Building with vcpkg Linking to libjson-

json-c 2.6k Dec 31, 2022
C++ header-only JSON library

Welcome to taoJSON taoJSON is a C++ header-only JSON library that provides a generic Value Class, uses Type Traits to interoperate with C++ types, use

The Art of C++ 499 Dec 27, 2022
A small header-only json library in C.

xjson A small header-only json library for C. The "unique" feature is that it allows use of the same code to serialize as well as deserialize, greatly

Stefan Bachmann 23 Jul 19, 2022
json_struct is a single header only C++ library for parsing JSON directly to C++ structs and vice versa

Structurize your JSON json_struct is a single header only library that parses JSON to C++ structs/classes and serializing structs/classes to JSON. It

Jørgen Lind 275 Dec 28, 2022
A small header-only library for converting data between json representation and c++ structs

Table of Contents Table of Contents What Is json_dto? What's new? v.0.3.0 v.0.2.14 v.0.2.13 v.0.2.12 v.0.2.11 v.0.2.10 v.0.2.9 v.0.2.8 v.0.2.7 v.0.2.6

Stiffstream 101 Dec 27, 2022
Very fast Python JSON parsing library

cysimdjson Fast JSON parsing library for Python, 7-12 times faster than standard Python JSON parser. It is Python bindings for the simdjson using Cyth

TeskaLabs 234 Jan 8, 2023
a header-file-only, JSON parser serializer in C++

PicoJSON - a C++ JSON parser / serializer Copyright © 2009-2010 Cybozu Labs, Inc. Copyright © 2011-2015 Kazuho Oku Licensed under 2-clause BSD license

Kazuho Oku 1k Dec 27, 2022
json-cpp is a C++11 JSON serialization library.

JSON parser and generator for C++ Version 0.1 alpha json-cpp is a C++11 JSON serialization library. Example #include <json-cpp.hpp> struct Foo {

Anatoly Scheglov 7 Oct 30, 2022
This is a JSON C++ library. It can write and read JSON files with ease and speed.

Json Box JSON (JavaScript Object Notation) is a lightweight data-interchange format. Json Box is a C++ library used to read and write JSON with ease a

Anhero inc. 110 Dec 4, 2022
A convenience C++ wrapper library for JSON-Glib providing friendly syntactic sugar for parsing JSON

This library is a wrapper for the json-glib library that aims to provide the user with a trivial alternative API to the API provided by the base json-

Rob J Meijer 17 Oct 19, 2022
Very low footprint JSON parser written in portable ANSI C

Very low footprint JSON parser written in portable ANSI C. BSD licensed with no dependencies (i.e. just drop the C file into your project) Never recur

James McLaughlin 1.2k Jan 5, 2023
Very simple C++ JSON Parser

Very simple JSON parser for c++ data.json: { "examples": [ { "tag_name": "a", "attr": [ { "key":

Amir Saboury 67 Nov 20, 2022
Very low footprint JSON parser written in portable ANSI C

Very low footprint JSON parser written in portable C89 (sometimes referred to as ANSI C). BSD licensed with no dependencies (i.e. just drop the C file

null 1.2k Dec 23, 2022
json-build is a zero-allocation JSON serializer compatible with C89

json-build is a zero-allocation JSON serializer compatible with C89. It is inspired by jsmn, a minimalistic JSON tokenizer.

Lucas Müller 31 Nov 16, 2022
🗄️ single header json parser for C and C++

??️ json.h A simple single header solution to parsing JSON in C and C++. JSON is parsed into a read-only, single allocation buffer. The current suppor

Neil Henning 544 Jan 7, 2023
single-header json parser for c99 and c++

ghh_json.h a single-header ISO-C99 (and C++ compatible) json loader. why? obviously this isn't the first json library written for C, so why would I wr

garrison hinson-hasty 14 Dec 1, 2022
A generator of JSON parser & serializer C++ code from structure header files

JSON-CPP-gen This is a program that parses C++ structures from a header file and automatically generates C++ code capable of serializing said structur

Viktor Chlumský 12 Oct 13, 2022
A C++17 single-file header-only library to wrap RapidJSON SAX interface

A C++17 single-file header-only library for RapidJSON SAX interface

null 5 Nov 4, 2022
Lightweight, header-only, C++17 configuration library

uconfig C++ header-only library to parse and emit multi-format configuration for your app. For example, you can parse JSON-file into the config and th

Tinkoff.ru 15 Dec 2, 2022