A tiny JSON library for C++11.

Related tags

JSON json11
Overview

json11

json11 is a tiny JSON library for C++11, providing JSON parsing and serialization.

The core object provided by the library is json11::Json. A Json object represents any JSON value: null, bool, number (int or double), string (std::string), array (std::vector), or object (std::map).

Json objects act like values. They can be assigned, copied, moved, compared for equality or order, and so on. There are also helper methods Json::dump, to serialize a Json to a string, and Json::parse (static) to parse a std::string as a Json object.

It's easy to make a JSON object with C++11's new initializer syntax:

Json my_json = Json::object {
    { "key1", "value1" },
    { "key2", false },
    { "key3", Json::array { 1, 2, 3 } },
};
std::string json_str = my_json.dump();

There are also implicit constructors that allow standard and user-defined types to be automatically converted to JSON. For example:

class Point {
public:
    int x;
    int y;
    Point (int x, int y) : x(x), y(y) {}
    Json to_json() const { return Json::array { x, y }; }
};

std::vector<Point> points = { { 1, 2 }, { 10, 20 }, { 100, 200 } };
std::string points_json = Json(points).dump();

JSON values can have their values queried and inspected:

Json json = Json::array { Json::object { { "k", "v" } } };
std::string str = json[0]["k"].string_value();

For more documentation see json11.hpp.

Comments
  • installation if json11 is added as a library works now

    installation if json11 is added as a library works now

    Please consider to change this, otherwise if you include the library like this:

    add_subdirectory(external/json11) set(JSON11_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external/json11) set(JSON11_LIBRARIES json11)

    it will work but if you run make install on your project it cannot find the json11.hpp and json11.pc file, because it searches in the wrong build directory.

    Also double check if this might cause trouble with other configuration. I haven't experienced side effects.

    opened by Pfeifenjoy 18
  • Detect comments

    Detect comments

    I know that comments are not defined in json standard, but many parsers do support them, and I find them useful. the patch is activated by a preprocessor macro and the original behavior can be restored by commenting its definition.

    opened by capitalaslash 11
  • Fails compiler checks for comparing floating point

    Fails compiler checks for comparing floating point

    If you have compile options set to throw a compile error on floating point comparison then there is trouble here:

    I don't know a suitable template specialization that works here. That does mean there is not one. https://github.com/dropbox/json11/blob/master/json11.cpp#L163

    This needs an "epsilon" comparison. https://github.com/dropbox/json11/blob/master/json11.cpp#L176

    and on the int templated https://github.com/dropbox/json11/blob/master/json11.cpp#L185 which is strange but easy to fix with a type cast.

    Will submit a PR if I find a good fix for everything.

    opened by crashmatt 7
  • Fix MSVC Compilation: Add MSVC warning flags

    Fix MSVC Compilation: Add MSVC warning flags

    When trying to build JSON11 on Microsoft Visual Studio 14 2015, the compiler would complain about the -Wextra and -Werror flags.

    This PR adds a check for the C++ compiler before adding the compiler specific flags

    opened by jnguyen75 6
  • Language issue causes dangerous pattern for nested arrays

    Language issue causes dangerous pattern for nested arrays

    Issue for tracking a long-standing issue which was never tracked publicly before. It's natural to want to construct a nested JSON array as follows: Json nested_array = Json::array { Json::array { 1, 2, 3 } }; This used to work as expected, until a language standard change DR1467 which caused the array constructor to be interpreted as a move instead of creating a nested array from an initializer_list. This is only an issue for single-element arrays, since 2 elements would break the ambiguity and be interpreted as an initializer_list.

    Most new compilers have the new dangerous behavior now. There's a "canary" in the unit test which is meant to point out whether your compiler has the bad behavior: https://github.com/dropbox/json11/blob/master/test.cpp#L195

    There is a new issue being tracked by the standards committee on this, but I haven't seen any action. Latest status is here: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2137

    Meanwhile the best workaround is to build these nested arrays in multiple steps using push_back()

    bug wontfix 
    opened by artwyman 6
  • Use CXX_STANDARD to specify c++11 compile flags

    Use CXX_STANDARD to specify c++11 compile flags

    Uses CXX_STANDARD to specify a C++11 build, which avoids issues when a build contains C files.

    Fixes #70

    The tests seem to fail on my laptop, with or without this change (same output)

    build ▹ ./json11_test
    k1: v1
    k3: ["a", 123, true, false, null]
        - "a"
        - 123
        - true
        - false
        - null
    Result: {"a": 1, "b": "text", "c": [1, 2, 3]}
    Result: {}
    Failed: malformed comment
    Failed: unexpected end of input inside inline comment
    Failed: unexpected end of input inside comment
    Failed: unexpected end of input inside multi-line comment
    obj: {"k1": "v1", "k2": 42, "k3": ["a", 123, true, false, null]}
    Assertion failed: (nested_array.array_items().size() == 1), function json11_test, file /Users/adam/workspace/json11/test.cpp, line 198.
    Abort trap: 6
    
    opened by admsyn 6
  • changed int type to intmax_t

    changed int type to intmax_t

    I need to serialize value (long timestamp in 10^7 Hz timer) exactly as int, so I added support for uint64_t integers on 64-bit platforms via intmax_t type.

    On 32-bit platforms (no under my hand to test) everything should work well.

    opened by theambient 6
  • How to parse mutlidimension array using json11 ?

    How to parse mutlidimension array using json11 ?

    Here is the sample response of one of my apis. And I would like to parse it using json11.

    {
      "status": 1,
      "message": {
        "fundNames": [
          "SBI Premier Liquid Fund - Institutional - Growth",
          "SBI Premier Liquid Fund - Institutional - Growth"
        ],
        "fundNavs": [
          [
            {
              "date": "2017-02-22",
              "nav": 2552.4454
            },
            {
              "date": "2017-02-21",
              "nav": 2551.9707
            }
          ],
          [
            {
              "date": "2017-02-22",
              "nav": 2552.4454
            },
            {
              "date": "2017-02-21",
              "nav": 2551.9707
            },
            {
              "date": "2017-02-18",
              "nav": 2550.6512
            }
          ]
        ]
      }
    }
    

    Here is my try

            string inputError;
            auto y = Json::parse(r.text, inputError);
            auto status = y["status"].int_value();
            if (status == 1) {
                for (auto &k: y["message"].array_items()) {
                    map<string, double> data;
                    for (auto &m : k[fundNavs].array_items()) {
                        auto nav = m["nav"].number_value();
                        auto nDate = m["date"].string_value();
                        data[nDate] = nav;
                    }
                }
            }
    
    
    opened by Shravan40 5
  • operator== could be faster by checking node identity

    operator== could be faster by checking node identity

    Story

    When comparing two nodes we can speed up use cases where we reuse node instances partially or totally:

    Json my_json = Json::object {
        { "key1", "value1" },
        { "key2", false },
        { "key3", Json::array { 1, 2, 3 } },
    };
    auto my_other_json = my_json;
    if (my_json == my_other_json)
    {
        ...
    }
    

    Two nodes sharing a portion of nodes:

    Json common = Json::object {
        { "key1", "value1" },
        { "key2", false },
        { "key3", Json::array { 1, 2, 3 } },
    };
    Json a = Son::object {
        { "common", common },
        { "extra value", "value1" }
    }
    Json b = Son::object {
        { "common", common },
        { "extra value", "value1" }
    }
    if (a == b) {
        ...
    }
    

    It may be useful to apply the same concept also for operator<, in such case would always return false:

    bool Json::operator< (const Json &other) const {
        if (m_ptr == other.m_ptr)
            return false;
        if (m_ptr->type() != other.m_ptr->type())
            return m_ptr->type() < other.m_ptr->type();
        return m_ptr->less(other.m_ptr.get());
    }
    

    These little changes would open memory + CPU optimisations of this sort:

    Json reuse_instances(Json new_node)
    {
       static std::set<Json> known_values;
    
       auto it = used_values.find(new_node);
       if (it != used_values.end()) {
           return it->second;
       }
    
       // may recursively do this for member nodes of object and arrays
       ...
    
       known_values.insert(new_node);
       return node;
    }
    
    ...
    
    Json my_object = reuse_instances(Json(Json::object {
        { "key1", "value1" },
        { "key2", false },
        { "key3", Json::array { 1, 2, 3 } },
    }));
    
    opened by rressi 5
  • Interchangable string class

    Interchangable string class

    I'm using a different string class than std::string. It would be good to add this either as a #define or a template parameter which defaults to std::string.

    If so, is this something which you would accept into the code base?

    Then, which method would you prefer?

    If it would be a define, it should be something like: #ifndef JSON11_STRING_TYPE #define JSON11_STRING_TYPE std::string #endif

    I have a domain-specific vector class as well, which might be useful to tweak as well...

    opened by jaw 5
  • Add cmake option for DR1467 canary tests

    Add cmake option for DR1467 canary tests

    This PR adds a cmake option for the DR 1467 tests, as described in PR #71

    That said, the test output seems to be the same regardless. This is the output after applying this PR, with an extra debug line printed in the relevant canary section of the tests

    [email protected]:~/workspace/json11/build$ cmake ..
    -- The CXX compiler identification is GNU 5.4.0
    -- Check for working CXX compiler: /usr/bin/c++
    -- Check for working CXX compiler: /usr/bin/c++ -- works
    -- Detecting CXX compiler ABI info
    -- Detecting CXX compiler ABI info - done
    -- Detecting CXX compile features
    -- Detecting CXX compile features - done
    -- Configuring done
    -- Generating done
    -- Build files have been written to: /home/adam/workspace/json11/build
    [email protected]:~/workspace/json11/build$ make
    Scanning dependencies of target json11
    [ 25%] Building CXX object CMakeFiles/json11.dir/json11.cpp.o
    [ 50%] Linking CXX static library libjson11.a
    [ 50%] Built target json11
    Scanning dependencies of target json11_test
    [ 75%] Building CXX object CMakeFiles/json11_test.dir/test.cpp.o
    [100%] Linking CXX executable json11_test
    [100%] Built target json11_test
    [email protected]:~/workspace/json11/build$ ./json11_test
    k1: v1
    k3: ["a", 123, true, false, null]
        - "a"
        - 123
        - true
        - false
        - null
    Result: {"a": 1, "b": "text", "c": [1, 2, 3]}
    Result: {}
    Failed: malformed comment
    Failed: unexpected end of input inside inline comment
    Failed: unexpected end of input inside comment
    Failed: unexpected end of input inside multi-line comment
    obj: {"k1": "v1", "k2": 42, "k3": ["a", 123, true, false, null]}
    -- performing canary test for DR1467
    {"key1": "value1", "key2": false, "key3": [1, 2, 3]}
    [[1, 2], [10, 20], [100, 200]]
    [email protected]:~/workspace/json11/build$ cmake -D JSON11_ENABLE_DR1467_CANARY=off ..
    -- Configuring done
    -- Generating done
    -- Build files have been written to: /home/adam/workspace/json11/build
    [email protected]:~/workspace/json11/build$ make
    [ 25%] Building CXX object CMakeFiles/json11.dir/json11.cpp.o
    [ 50%] Linking CXX static library libjson11.a
    [ 50%] Built target json11
    [ 75%] Building CXX object CMakeFiles/json11_test.dir/test.cpp.o
    [100%] Linking CXX executable json11_test
    [100%] Built target json11_test
    [email protected]:~/workspace/json11/build$ ./json11_test
    k1: v1
    k3: ["a", 123, true, false, null]
        - "a"
        - 123
        - true
        - false
        - null
    Result: {"a": 1, "b": "text", "c": [1, 2, 3]}
    Result: {}
    Failed: malformed comment
    Failed: unexpected end of input inside inline comment
    Failed: unexpected end of input inside comment
    Failed: unexpected end of input inside multi-line comment
    obj: {"k1": "v1", "k2": 42, "k3": ["a", 123, true, false, null]}
    -- NOT performing canary test for DR1467
    {"key1": "value1", "key2": false, "key3": [1, 2, 3]}
    [[1, 2], [10, 20], [100, 200]]
    
    enhancement 
    opened by admsyn 5
  • Fixes to CMake for MSVC build

    Fixes to CMake for MSVC build

    MSVC build was failing under Visual Studio 2017 with CMake v3.15.5 and v3.16.2 generated project files.

    Compiler cl.exe was failing with following error code for all GCC specific compiler flags

    cl : Command line error D8021: invalid numeric argument '/Wextra'
    

    CHECK_CXX_COMPILER_FLAG() evaluates with GCC specific compiler flags to positive result.

    bug 
    opened by m4x1m1l14n 1
  • Warning '-Werror=overloaded-virtual' with gcc-5.1.0 --std=c++14

    Warning '-Werror=overloaded-virtual' with gcc-5.1.0 --std=c++14

    Please review and merge this pull request : https://github.com/random-basad/json11/commit/7a03087db4898e50d41d06e1fd7945c92a109bd4

    Thanks. @artwyman

    /home/genstor/toolchain/json11-master/json/json11.hpp:228:25: error: 'virtual const json11::Json& json11::JsonValue::operator[](const string&) const' was hidden [-Werror=overloaded-virtual]
         virtual const Json &operator[](const std::string &key) const;
                             ^
    /home/genstor/toolchain/json11-master/json/json11.cpp:206:18: error:   by 'virtual const json11::Json& json11::JsonArray::operator[](size_t) const' [-Werror=overloaded-virtual]
         const Json & operator[](size_t i) const override;
                      ^
    In file included from /home/genstor/toolchain/json11-master/json/json11.cpp:22:0:
    /home/genstor/toolchain/json11-master/json/json11.hpp:226:25: error: 'virtual const json11::Json& json11::JsonValue::operator[](size_t) const' was hidden [-Werror=overloaded-virtual]
         virtual const Json &operator[](size_t i) const;
                             ^
    /home/genstor/toolchain/json11-master/json/json11.cpp:214:18: error:   by 'virtual const json11::Json& json11::JsonObject::operator[](const string&) const' [-Werror=overloaded-virtual]
         const Json & operator[](const string &key) const override;
                      ^
    
    bug enhancement 
    opened by mohitmv 1
  • ASAN reports runtime error

    ASAN reports runtime error

    With set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -fno-omit-frame-pointer -fsanitize=address,undefined") set (CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address,undefined")

    I get the following report:

    0x603000115b40: note: object has invalid vptr
     18 00 00 66  00 f1 21 58 55 55 00 00  01 00 00 00 01 00 00 00  b8 f2 21 58 55 55 00 00  be be be be
                  ^~~~~~~~~~~~~~~~~~~~~~~
                  invalid vptr
    /usr/include/c++/8/bits/shared_ptr_base.h:728:4: runtime error: member call on address 0x603000115b40 which does not point to an object of type '_Sp_counted_base'
    0x603000115b40: note: object has invalid vptr
     18 00 00 66  00 f1 21 58 55 55 00 00  02 00 00 00 01 00 00 00  b8 f2 21 58 55 55 00 00  be be be be
                  ^~~~~~~~~~~~~~~~~~~~~~~
                  invalid vptr
    

    This is with git cloned a few moments ago. I can dig deeper a bit later. Have you tested json11 with asan?

    question 
    opened by tksuoran 1
  • auto casting

    auto casting

    I added the following to json11.hpp

     /// @weepy additions
            operator long() {
                return (long) int_value();
            }
            
            operator int() {
                return int_value();
            }
            operator float() {
                return (float) number_value();
            }
            operator double() {
                return (double) number_value();
            }
            operator std::string() {
                return string_value();
            }
            operator bool() {
                return bool_value();
            }
            
            operator object() {
                return object_items();
            }
            
            operator array() {
                return array_items();
            }
    

    It makes using json11 much more convenient as the compiler will auto cast your variables for you, eg:
    int id = myJson["id"];

    enhancement 
    opened by weepy 4
Releases(v1.0.0)
Owner
Dropbox
Dropbox
A tiny JSON library for C++11.

json11 json11 is a tiny JSON library for C++11, providing JSON parsing and serialization. The core object provided by the library is json11::Json. A J

Dropbox 2.4k Dec 31, 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
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
An easy-to-use and competitively fast JSON parsing library for C++17, forked from Bitcoin Cash Node's own UniValue library.

UniValue JSON Library for C++17 (and above) An easy-to-use and competitively fast JSON parsing library for C++17, forked from Bitcoin Cash Node's own

Calin Culianu 24 Sep 21, 2022
A Haskell library for fast decoding of JSON documents using the simdjson C++ library

hermes A Haskell interface over the simdjson C++ library for decoding JSON documents. Hermes, messenger of the gods, was the maternal great-grandfathe

Josh Miller 36 Dec 5, 2022
C library for encoding, decoding and manipulating JSON data

Jansson README Jansson is a C library for encoding, decoding and manipulating JSON data. Its main features and design principles are: Simple and intui

Petri Lehtinen 2.7k Dec 31, 2022
A very sane (header only) C++14 JSON library

JeayeSON - a very sane C++14 JSON library JeayeSON was designed out of frustration that there aren't many template-based approaches to handling JSON i

Jeaye Wilkerson 128 Nov 28, 2022
A C++ library for interacting with JSON.

JsonCpp JSON is a lightweight data-interchange format. It can represent numbers, strings, ordered sequences of values, and collections of name/value p

null 6.9k Dec 31, 2022
A killer modern C++ library for interacting with JSON.

JSON Voorhees Yet another JSON library for C++. This one touts new C++11 features for developer-friendliness, an extremely slow-speed parser and no de

Travis Gockel 124 Oct 26, 2022
a JSON parser and printer library in C. easy to integrate with any model.

libjson - simple and efficient json parser and printer in C Introduction libjson is a simple library without any dependancies to parse and pretty prin

Vincent Hanquez 260 Nov 21, 2022
Lightweight JSON library written in C.

About Parson is a lightweight json library written in C. Features Full JSON support Lightweight (only 2 files) Simple API Addressing json values with

Krzysztof Gabis 1.2k Dec 31, 2022
QJson is a qt-based library that maps JSON data to QVariant objects.

QJson JSON (JavaScript Object Notation) is a lightweight data-interchange format. It can represents integer, real number, string, an ordered sequence

Flavio Castelli 273 Dec 2, 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 fast streaming JSON parsing library in C.

********************************************************************** This is YAJL 2. For the legacy version of YAJL see https

Lloyd Hilaiel 2.1k Jan 1, 2023
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
Immediate Mode JSON Serialization Library in C

JIM Immediate Mode JSON Serialization Library in C. Similar to imgui but for generating JSON. Example example.c: #include <stdio.h> #define JIM_IMPLE

Tsoding 33 Dec 13, 2022
📟 JSON library for Arduino and embedded C++. Simple and efficient.

ArduinoJson is a C++ JSON library for Arduino and IoT (Internet Of Things). Features JSON deserialization Optionally decodes UTF-16 escape sequences t

Benoît Blanchon 6k Jan 3, 2023