This is a JSON C++ library. It can write and read JSON files with ease and speed.

Related tags

JSON JsonBox
Overview

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 and speed.

Things it does:

  • Follows the standards established on http://json.org/
  • Read and write JSON in UTF-8
  • Uses the STL streams for input and output
  • Generated JSON can be indented and pretty or compact and hard-to-read
  • Does not crash when the JSON input contains errors, it simply tries to interpret as much as it can

Things it does not do:

  • Read JSON in UTF-16 or UTF-32
  • Keep the order of the members in objects (the standard doesn't require keeping the order)
  • Write useful error messages when the JSON input contains errors

The library wasn't designed with multi-threading in mind.

The class reference can be found here.

Android

mkdir build
cd build && mkdir armeabi-v7a
cd armeabi-v7a
cmake -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_NDK=<android_ndk> \
        -DCMAKE_ANDROID_ARCH_ABI=armeabi-v7a -DCMAKE_ANDROID_STL_TYPE=c++_static \ 
        -DCMAKE_BUILD_TYPE=Release -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang \ 
        -DCMAKE_INSTALL_PREFIX=<android_ndk>/sources/third_party/JsonBox ../..
make install

You should replace <android_ndk> with the actual folder.

Issues
  • Missing exports

    Missing exports

    There are no export macros on JsonBox classes (something like JB_EXPORT?), it would be useful if the library is compiled as a dynamic library, or statically linked to a dynamic library. (Currently, I have to statically compile the library with every module of my game engine, multiplying the binary size).

    opened by Zylann 14
  • getDouble() fails if number has no decimal digits and no exponent

    getDouble() fails if number has no decimal digits and no exponent

    When writing double to a JSON file, some numbers are exported without decimal digits (which by itself is fine and shouldn't be changed):

                        "coeffs" : [
                                -4.14925e-05,
                                -3.12482e-05,
                                1,
                                -0.00257958
                        ],
    

    However when loading this file, getDouble() returns the third element as 0.0 because it is treated as an integer. I think getDouble() should return integer values as doubles, because there is no loss involved in the conversion and the current behavior is broken.

    enhancement 
    opened by rhuitl 7
  • OutputFilter::setbuf does not overload

    OutputFilter::setbuf does not overload

    The current implementation of OutputFilter triggers a -Woverloaded-virtual warning because its setbuf method hides std::streambuf::setbuf:

    /usr/include/c++/4.8.3/streambuf:591:7: error: ‘std::basic_streambuf<_CharT, _Traits>* std::basic_streambuf<_CharT, _Traits>::setbuf(std::basic_streambuf<_CharT, _Traits>::char_type*, std::streamsize) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_streambuf<_CharT, _Traits>::char_type = char; std::streamsize = long int]’ was hidden [-Werror=overloaded-virtual]
           setbuf(char_type*, streamsize)
           ^
    In file included from jsonbox/src/Array.cpp:5:0:
    jsonbox/include/JsonBox/OutputFilter.h:94:27: error:   by ‘std::streambuf* JsonBox::OutputFilter<Inserter>::setbuf(char*, int) [with Inserter = JsonBox::Indenter; std::streambuf = std::basic_streambuf<char>]’ [-Werror=overloaded-virtual]
       virtual std::streambuf *setbuf(char *p, int len) {
                               ^
    

    Considering that std::streambuf::setbuf is a virtual method, it would appear that this is intended to be an overload. Unfortunately it is not an overload due to a mismatch in parameter types. The second parameter has type int, but the correct type for this virtual method is std::streamsize (see e.g. http://en.cppreference.com/w/cpp/io/basic_streambuf/pubsetbuf and/or the above compiler diagnostic).

    opened by mwoehlke-kitware 4
  • Explain how to check if object contains an attribute in docs

    Explain how to check if object contains an attribute in docs

    It took me some time to find this and I'm still not sure if it was the proper way.

    if (object.find("property") != object.end())
    

    It would be even better if getXXX() methods could supply a default value. For example, I want to distinguish when some integer value is zero, vs when it is not present in JSON file at all.

    Example:

    int x = o["something"].getInteger(10);
    

    would mean: get the value and if it does not exist, return 10.

    opened by mbabuskov 3
  • Problem parsing large file

    Problem parsing large file

    I have a JSON file, produced by another program. I'm having a problem parsing it. As a test I wrote a three-line program:

    JsonBox::Value meta; meta.loadFromFile("file_In.txt"); meta.writeToFile("file_out.txt");

    The "file_in.txt" is 22 KB; "file_Out.txt" is only 7 KB and much of the data is missing.

    If someone can try this, I have put the file in DropBox:

    http://db.tt/lOF8PiX6

    Thanks.

    Alan

    opened by AlanLyttonJones 3
  • Allow building shared library

    Allow building shared library

    Don't force library to be built static, but instead honor CMAKE_BUILD_SHARED. Update install locations to support building a shared library, and to honor LIB_SUFFIX.

    opened by mwoehlke-kitware 2
  • Add support for unsigned integers

    Add support for unsigned integers

    When I try to serialize unsigned integers, it results in an ambiguous call (bool, char*, int), and I'm forced to cast them as signed integers (int) to have a perfect match.

    opened by Zylann 2
  • Accessing JsonBox::Object index [0]

    Accessing JsonBox::Object index [0]

    Bug at line 26?
    Lines 27 and 28 work if 26 commented out! ===============temp2.json====================== {"name" : "tommy", "entries" : [ "I am a string", 234, { "deep":777, "name":null } ], "age" : 23, "salary" : 25.10, "male" : true } ============== error ==================== c:\toolbox\cpp\src\json\src\main.cpp(26) : error C2593: 'operator [' is ambiguous c:\toolbox\cpp\src\json\src\Value.h(241): could be 'JsonBox::Value &Json Box::Value::operator ' c:\toolbox\cpp\src\json\src\Value.h(228): or 'JsonBox::Value &Json Box::Value::operator [](const char *)' while trying to match the argument list '(JsonBox::Object::mapped_type,int)' ============== code ======================= 01 //...Input from a file 02 JsonBox::Value v2; 03 v2.loadFromFile("temp2.json"); 04 std::cout << v2 << std::endl; 05 std::cout << "Type=" << v2.getType() << std::endl; 06 if (v2.isObject()) std::cout << "Object" << std::endl; 07 08 // Print out from Value 09 std::cout << "===================================\n"; 10 JsonBox::Object o2 = v2.getObject(); 11 std::cout << "Size=" << o2.size() << std::endl; 12 std::cout << "Name=" << o2["name"] << std::endl; 13 std::cout << "Deep=" << o2["entries"] << std::endl; 14 15 for (JsonBox::Object::const_iterator i = o2.begin(); i != o2.end(); i++) 16 { 17 std::string key; 18 JsonBox::Value v3; 19 key = i->first; 20 v3 = i->second; 21 std::cout << "ITER: " << key << ":" << i->second << 22 ":" << v3.getType() << std::endl; 23 //std::cout << typeid(i->second).name() << std::endl; 24 } 25 26 std::cout << "Deep[0]=" << o2["entries"][0] << std::endl; 27 std::cout << "Deep[1]=" << o2["entries"][1] << std::endl; 28 std::cout << "Deep[2]=" << o2["entries"][2] << std::endl; 29 std::cout << "...End test" << std::endl; 30 }

    opened by varmint2all 2
  • Value::tryGetBoolean()  does not return defaultValue as documented

    Value::tryGetBoolean() does not return defaultValue as documented

    The documentation indicates that Value::tryGetBoolean() returns Value's boolean value, or defaultValue if the value doesn't contain a boolean. However, if the value doesn't contain a boolean it actually returns EMPTY_BOOL instead of returning defaultValue.

    opened by gwesterberg 1
  • Add fPIC definition for static compiling into shared libraries

    Add fPIC definition for static compiling into shared libraries

    We are developing an API library where we would like to have a single shared library that includes JsonBox functionality as well our custom code. To statically compile in the JsonBox code, we need to add the fPIC definition to the CMakeLists.txt file. Can we add this to the JsonBox main branch as is seems generally useful. Simple adding the following to line 7 of the CMakeLists.txt file should work.

    add_definitions(-fPIC)

    opened by sfeller 1
  • Cannot load files with CRLF line endings

    Cannot load files with CRLF line endings

    I'm using JsonBox on Linux, Windows and Mac. When it creates a JSON file on Windows, it has CRLF line endings. However, when loading this file, JsonBox spits errors like this:

    Expected '"', got '}', ignoring it.

    If I use some tool and manually change the line-endings to LF, JsonBox loads it fine.

    This does not happen with all files, only larger ones. Here's an example file that fails:

    http://bigosaur.com/checkpoint2.json

    If it matters, I'm using 32bit build on a 64bit Windows 8.1 machine to test.

    opened by mbabuskov 1
  • cmake maximum version

    cmake maximum version

    Hi, i am having trouble building a project, because I use cmake 3.17. JsonBox project has explicit maximum version of cmake set to 3.14. Is something changed in cmake making it is useless in building your project or what is the issue with newer versions of cmake?

    Best regards, Klemen

    opened by kb2623 0
  • unix timestamp

    unix timestamp

    Hi, when I try to convert this json:

    {"job":{"submitTime":1526542607961,"startTime":1526542616091,"finishTime":1526542638046,"id":"job_1526459673820_0015","name":"oozie:launcher:T=shell:W=ec-coresyf_dcs-optical-bathymetry_OpticalBathymetry-ACRI:A=T2PUSHRESULTS:ID=0000002-180516103505431-oozie-oozi-W","queue":"default","user":"oozie","state":"SUCCEEDED","mapsTotal":1,"mapsCompleted":1,"reducesTotal":0,"reducesCompleted":0,"uberized":false,"diagnostics":"","avgMapTime":19108,"avgReduceTime":0,"avgShuffleTime":0,"avgMergeTime":0,"failedReduceAttempts":0,"killedReduceAttempts":0,"successfulReduceAttempts":0,"failedMapAttempts":0,"killedMapAttempts":0,"successfulMapAttempts":1}}

    all unix timestamps are converted badly

    failedMapAttempts:0 failedReduceAttempts:0 finishTime:2147483647 id:job_1526459673820_0015 killedMapAttempts:0 killedReduceAttempts:0 mapsCompleted:1 mapsTotal:1 name:oozie:launcher:T=shell:W=ec-coresyf_dcs-optical-bathymetry_OpticalBathymetry-ACRI:A=T2PUSHRESULTS:ID=0000002-180516103505431-oozie-oozi-W reducesCompleted:0 reducesTotal:0 startTime:2147483647 state:SUCCEEDED submitTime:2147483647 successfulMapAttempts:1 successfulReduceAttempts:0

    void testConvert(){
    	std::string JSON{"{\"job\":{\"submitTime\":1526542607961,\"startTime\":1526542616091,\"finishTime\":1526542638046,\"id\":\"job_1526459673820_0015\",\"name\":\"oozie:launcher:T=shell:W=ec-coresyf_dcs-optical-bathymetry_OpticalBathymetry-ACRI:A=T2PUSHRESULTS:ID=0000002-180516103505431-oozie-oozi-W\",\"queue\":\"default\",\"user\":\"oozie\",\"state\":\"SUCCEEDED\",\"mapsTotal\":1,\"mapsCompleted\":1,\"reducesTotal\":0,\"reducesCompleted\":0,\"uberized\":false,\"diagnostics\":\"\",\"avgMapTime\":19108,\"avgReduceTime\":0,\"avgShuffleTime\":0,\"avgMergeTime\":0,\"failedReduceAttempts\":0,\"killedReduceAttempts\":0,\"successfulReduceAttempts\":0,\"failedMapAttempts\":0,\"killedMapAttempts\":0,\"successfulMapAttempts\":1}}"};
    	JsonBox::Value jStatus;
    	jStatus.loadFromString(JSON);
    	JsonBox::Value v = jStatus["job"];
    	std::cout  << "v[\"submitTime\"]: " <<  v["submitTime"]  << " - getToString():" << v["submitTime"].getToString() << " - getDouble(): " <<  v["submitTime"].getDouble() << " - getFloat(): " <<  v["submitTime"].getFloat() << " - getType(): "  <<  v["submitTime"].getType() << "\n";
    	std::cout<< jStatus;
    }
    

    Result:

    v["submitTime"]: 2147483647 - getToString():2147483647 - getDouble(): 2.14748e+09 - getFloat(): 2.14748e+09 - getType(): 1 { "job" : { "avgMapTime" : 19108, "avgMergeTime" : 0, "avgReduceTime" : 0, "avgShuffleTime" : 0, "diagnostics" : "", "failedMapAttempts" : 0, "failedReduceAttempts" : 0, "finishTime" : 2147483647, "id" : "job_1526459673820_0015", "killedMapAttempts" : 0, "killedReduceAttempts" : 0, "mapsCompleted" : 1, "mapsTotal" : 1, "name" : "oozie:launcher:T=shell:W=ec-coresyf_dcs-optical-bathymetry_OpticalBathymetry-ACRI:A=T2PUSHRESULTS:ID=0000002-180516103505431-oozie-oozi-W", "queue" : "default", "reducesCompleted" : 0, "reducesTotal" : 0, "startTime" : 2147483647, "state" : "SUCCEEDED", "submitTime" : 2147483647, "successfulMapAttempts" : 1, "successfulReduceAttempts" : 0, "uberized" : false, "user" : "oozie" } }

    The timestamps are in milliseconds and i can't change the json

    opened by t2rdirienzo 1
  • Position-independent code flag needed in some cases

    Position-independent code flag needed in some cases

    When linking against a debug, static version of JsonBox, I needed to add the setting set(CMAKE_POSITION_INDEPENDENT_CODE ON) in JsonBox's CMakeLists.txt before making and installing it to my system. Otherwise, I get the linker error described in this SO question.

    I'm not necessarily asking that this setting be added into JsonBox in all cases, nor am I asking that it even be added in any case; I am just bringing to light a problem I faced and making sure others are aware of it. (This is the first time I've hit this issue, but if it's a common problem, feel free to chalk it up to my ignorance :smile:)

    Note that for any users running into this issue, another solution (I suspect) is to add JsonBox as a target within your CMake-managed project, instead of depending on an installed version on your system. You can then add the CMAKE_POSITION_INDEPENDENT_CODE ON setting to the JsonBox target.

    opened by gussmith23 0
  • Value::operator<< overload is not thread-safe

    Value::operator<< overload is not thread-safe

    Running the following code produces a segfault:

    #include "JsonBox.h"
    #include <ctime>
    #include <sstream>
    #include <chrono>
    #include <thread>
    #include <future>
    
    int main()
    {
        std::srand(std::time(0));
        int numThings = 50;
    
        std::promise<void> p;
        std::shared_future<void> f = p.get_future().share();
    
        for(int i = 0; i < numThings; i++) {
            std::thread t([f](){
                    JsonBox::Value val;
                    val[std::to_string(std::rand())] = std::rand();
                    f.get();
    
                    // This code segfaults
                    std::cout << val << std::endl;
    
                    // This code is fine
                    /*
                    std::ostringstream os;
                    val.writeToStream(os);
                    std::string print = os.str();
                    std::cout << print << std::endl;
                    */
                });
            t.detach();
        }
        std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
        p.set_value();
        std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
    }
    

    The Values that are printed out are all created in different threads/scopes. It seems as though the overload itself is what is causing the segfault. My guess is it has to do with Value.cpp lines https://github.com/anhero/JsonBox/blob/a6d8255e1ee33281e6ca317b122d9ac5af135a65/src/Value.cpp#L1247 and https://github.com/anhero/JsonBox/blob/a6d8255e1ee33281e6ca317b122d9ac5af135a65/src/Value.cpp#L1259 This turns out to be very annoying when debugging code from multiple threads.

    opened by camerongivler 0
  • Infinite loop in Value::readObject(...) stream checking

    Infinite loop in Value::readObject(...) stream checking

    Playing around with the afl fuzzer, I have encountered a hang in the (time of writing) trunk code.

    Test case: JsonBox_hang00.json.txt

    Sure the input is not valid JSON, but it triggers something interesting.

    Using Value::loadFromString(...) which uses Value::loadFromStream(...) which in the Structural::BEGIN_OBJECT case calls Value::readObject(...) we end up in the innermost while loop of readObject.

    That loop runs infinite since input.eof() stays low, but in debugging I can see that input.fail() goes high, properly due to the fuzzed bad input file.

    Referring to the truth table at http://en.cppreference.com/w/cpp/io/basic_ios/eof a possible fix could be to use input.good() instead of !input.eof(), but I'll leave that up to the developers.

    Note that !input.eof() is used a number of places in Value.cpp.

    opened by PerGraa 0
Owner
Anhero inc.
Anhero inc.
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.5k Jun 22, 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 4 Dec 31, 2019
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 16 May 10, 2022
json2cpp is compiles a json file into static constexpr data structures that can be used at compile time or runtime

json2cpp json2cpp is compiles a json file into static constexpr data structures that can be used at compile time or runtime. Features Literally 0 runt

Jason Turner 158 Jun 13, 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ý 8 May 2, 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 24 Jun 20, 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 10 Aug 31, 2021
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 35 May 26, 2022
A C++ library for localization using GNU gettext po files, based on boost spirit

spirit-po spirit-po is a header-only C++11 library that you can use for localization within the GNU gettext system, instead of using libintl. spirit-p

Chris Beck 39 Apr 29, 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 5.7k Jun 27, 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.6k Jun 30, 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 Jun 18, 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 227 Jun 16, 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 97 Jun 20, 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 Jun 7, 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.5k Jun 23, 2022
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.3k Jun 22, 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 125 Mar 4, 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.1k Jun 29, 2022