A C++ library for interacting with JSON.

JsonCpp

badge badge badge Coverage Status

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

JsonCpp is a C++ library that allows manipulating JSON values, including serialization and deserialization to and from strings. It can also preserve existing comment in unserialization/serialization steps, making it a convenient format to store user input files.

Documentation

JsonCpp documentation is generated using Doxygen.

A note on backward-compatibility

  • 1.y.z is built with C++11.
  • 0.y.z can be used with older compilers.
  • 00.11.z can be used both in old and new compilers.
  • Major versions maintain binary-compatibility.

Special note

The branch 00.11.zis a new branch, its major version number 00 is to show that it is different from 0.y.z and 1.y.z, the main purpose of this branch is to make a balance between the other two branches. Thus, users can use some new features in this new branch that introduced in 1.y.z, but can hardly applied into 0.y.z.

Using JsonCpp in your project

The vcpkg dependency manager

You can download and install JsonCpp using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install jsoncpp

The JsonCpp port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Amalgamated source

https://github.com/open-source-parsers/jsoncpp/wiki/Amalgamated-(Possibly-outdated)

The Meson Build System

If you are using the Meson Build System, then you can get a wrap file by downloading it from Meson WrapDB, or simply use meson wrap install jsoncpp.

Other ways

If you have trouble, see the Wiki, or post a question as an Issue.

License

See the LICENSE file for details. In summary, JsonCpp is licensed under the MIT license, or public domain if desired and recognized in your jurisdiction.

Comments
  • Use a consistent target name for jsoncpp in CMake scripts

    Use a consistent target name for jsoncpp in CMake scripts

    The target name for the jsoncpp library would change based on whether we were building a static or shared library. This inconsistency made it difficult and unintuitive to pull in jsoncpp as a submodule in another repository and link to it directly via other CMake scripts.

    Having a consistent target name will allow libraries with their own CMake scripts to reliably refer to jsoncpp as a dependency. Example CMake script below shows how I would refer to jsoncpp as a dependency in my own parent project. Note that jsoncpp in this case is a submodule in my git repository.

    set( project_name my-project )
    
    project( ${project_name} )
    
    set( sources
        main.cpp
    )
    
    add_subdirectory( jsoncpp )
    
    add_executable( ${project_name} ${sources} )
    target_link_libraries( ${project_name} PRIVATE jsoncpp )
    

    Other Changes:

    • BUILD_SHARED_LIBS and BUILD_STATIC_LIBS removed in favor of JSONCPP_LIBRARY_TYPE, which allows you to pick either SHARED or STATIC library variations. This change was made to prevent both shared and static libraries being built at the same time. This isn't allowed anymore since we only generate 1 target for the jsoncpp library now.
    • Clean up closing statements for if conditions, functions, macros, and other entities. Newer versions of CMake do not require you to redundantly respecify the parameters to the opening arguments.
    • travis.sh build script updated to perform CMake generation in an out-of-source binary directory. This will prevent the temporary generated output files from intermixing into the source tree and allow for multiple generations with different configurations using the same source tree.
  • Building SHARED and STATIC library

    Building SHARED and STATIC library

    As I can see, it is currently not possible to build both versions, correct?

    Would a PR that offers this functionality be merged? I want to package a more recent version for debian, which requires .a and .so version of it.

  • Bug: can't create array more than 5 items

    Bug: can't create array more than 5 items

    test code is:

        int count = 5;
        Json::Value root;
        Json::Value item;
        root["array"] = Json::Value::nullRef;
        for (int i = 0; i < count; i++)
        {
            item["a"] = i;
            item["b"] = i;
            root["array"][i] = item;
        }
    

    the above code's result is wrong,

    {
       "array" : [
          {
             "a" : 0,
             "b" : 0
          }
       ]
    }
    

    but if when the count = 4, then the result is right:

    {
       "array" : [
          {
             "a" : 0,
             "b" : 0
          },
          {
             "a" : 1,
             "b" : 1
          },
          {
             "a" : 2,
             "b" : 2
          },
          {
             "a" : 3,
             "b" : 3
          }
       ]
    }
    
  • Fix non-rvalue Json::Value assignment operator (should copy, not move)

    Fix non-rvalue Json::Value assignment operator (should copy, not move)

    Pull request #635 has changed the behavior of non-rvalue assignment operator from copying the 'other' value to swapping with it. There is a lot of wrong with it.

    This pull request reverts to the earlier assignment operator, with 'other' passed by value rather than const&. Now that Json::Value has a move constructor, such assignment operator covers both move and non-move cases.

  • Memory leak issue in jsoncpp ver 0.10.7(0.y.z)

    Memory leak issue in jsoncpp ver 0.10.7(0.y.z)

    We tried to feed 128KB data in JSON parser API , which took almost 2MB of memory .

    Please find the below code for your reference ,

    if(!reader.parse(buf, root)) { return false; }

    Could you please provide your input on this .

    Thanks & Regards, Subitha.P

  • Failing ValueTest/integers unit test (32-bit gcc Linux RelWithDebInfo)

    Failing ValueTest/integers unit test (32-bit gcc Linux RelWithDebInfo)

    I'm building with CMake and getting the following error from the unit tests:

    Testing ValueTest/checkNormalizeFloatingPointStr: OK
    Testing ValueTest/memberCount: OK
    Testing ValueTest/objects: OK
    Testing ValueTest/arrays: OK
    Testing ValueTest/null: OK
    Testing ValueTest/strings: OK
    Testing ValueTest/bools: OK
    Testing ValueTest/integers: FAILED
    Testing ValueTest/nonIntegers: OK
    Testing ValueTest/compareNull: OK
    Testing ValueTest/compareInt: OK
    Testing ValueTest/compareUInt: OK
    Testing ValueTest/compareDouble: OK
    Testing ValueTest/compareString: OK
    Testing ValueTest/compareBoolean: OK
    Testing ValueTest/compareArray: OK
    Testing ValueTest/compareObject: OK
    Testing ValueTest/compareType: OK
    Testing ValueTest/offsetAccessors: OK
    Testing ValueTest/typeChecksThrowExceptions: OK
    Testing ReaderTest/parseWithNoErrors: OK
    Testing ReaderTest/parseWithNoErrorsTestingOffsets: OK
    Testing ReaderTest/parseWithOneError: OK
    Testing ReaderTest/parseChineseWithOneError: OK
    Testing ReaderTest/parseWithDetailError: OK
    Testing WriterTest/dropNullPlaceholders: OK
    * Detail of ValueTest/integers test failure:
    /home/eric/Development/jsoncpp/src/test_lib_json/main.cpp(664): kfint32max == val.asFloat()
      Expected: 2147483648
      Actual  : 2147483648
    25/26 tests passed (1 failure(s))
    make[2]: *** [jsoncpp/bin/jsoncpp_test] Error 1
    make[1]: *** [jsoncpp/src/test_lib_json/CMakeFiles/jsoncpp_test.dir/all] Error 2
    make: *** [all] Error 2
    

    Is this an issue in the code or maybe specific to my setup?

  • GCC6 Support

    GCC6 Support

    Hi!

    At Debian we are currently preparing the migration to GCC6. The following issues are currently affecting libjsoncpp.

    https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=811958

    Could you take a look at it?

  • move ctors

    move ctors

    • Add move constructor to Value::CZString
    • Add unit test for Value move constructor
    • Allow includer to specify in advance the value for JSON_HAS_RVALUE_REFERENCES

    rebased #264.

  • undefined reference to `Json::Value::Value(Json::ValueType)'

    undefined reference to `Json::Value::Value(Json::ValueType)'

    I use clion. I want to use json library. But i have soo many problems. Firstly undefined reference to `Json::Value::Value(Json::ValueType)'. How can i solve this problem.

  • Json testing with equals is failing.

    Json testing with equals is failing.

    I'm trying to test if 2 pieces of json is the same but having trouble with this one test. This is the console output below, is this a bug or am I doing equals testing wrong?

     FAILED:
      REQUIRE( returnJson == CEJsonHelper::parse( "{\"apiVersion\" : \"1.0.0\",\"inEffect\" : false,\"methodCaller\" : \"getDuckworthLewisStern\",\"oversRemainingIncludingBreaks\" : -1,\"oversUsedIncludingBreaks\" : -1,\"parScore\" : -1,\"projectedScore\" : -1,\"runsToWin\" : -1,\"runsToWinPerOver\" : -1,\"runsToWinPerOverAverage\" : -1,\"showResults\" : false,\"targetScore\" : -1,\"validResult\" : false,\"winningBy\" : -1,\"methodCaller\":\"getDuckworthLewisStern\"}") )
    with expansion:
    {
     "apiVersion" : "1.0.0",
      "inEffect" : false,
      "methodCaller" : "getDuckworthLewisStern",
      "oversRemainingIncludingBreaks" : -1,
      "oversUsedIncludingBreaks" : -1,
      "parScore" : -1,
      "projectedScore" : -1,
      "runsToWin" : -1,
      "runsToWinPerOver" : -1,
      "runsToWinPerOverAverage" : -1,
      "showResults" : false,
      "targetScore" : -1,
      "validResult" : false,
      "winningBy" : -1
      }
      ==
      {
      "apiVersion" : "1.0.0",
      "inEffect" : false,
      "methodCaller" : "getDuckworthLewisStern",
      "oversRemainingIncludingBreaks" : -1,
      "oversUsedIncludingBreaks" : -1,
      "parScore" : -1,
      "projectedScore" : -1,
      "runsToWin" : -1,
      "runsToWinPerOver" : -1,
      "runsToWinPerOverAverage" : -1,
      "showResults" : false,
      "targetScore" : -1,
      "validResult" : false,
      "winningBy" : -1
      }
    
  • isfinite compilation error

    isfinite compilation error

    Building CXX object myProject/third/CMakeFiles/third.dir/jsoncpp.cpp.o
    /home/vagrant/myProject/myProject/third/jsoncpp.cpp: In function ‘std::string Json::valueToString(double)’:
    /home/vagrant/myProject/myProject/third/jsoncpp.cpp:4049:21: error: ‘isfinite’ was not declared in this scope
       if (isfinite(value)) {
                         ^
    /home/vagrant/myProject/myProject/third/jsoncpp.cpp:4049:21: note: suggested alternative:
    In file included from /usr/include/c++/4.8/random:38:0,
                     from /usr/include/c++/4.8/bits/stl_algo.h:65,
                     from /usr/include/c++/4.8/algorithm:62,
                     from /home/vagrant/myProject/myProject/third/jsoncpp.cpp:2398:
    /usr/include/c++/4.8/cmath:596:5: note:   ‘std::isfinite’
         isfinite(_Tp __x)
         ^
    make[2]: *** [myProject/third/CMakeFiles/third.dir/jsoncpp.cpp.o] Error 1
    make[1]: *** [myProject/third/CMakeFiles/third.dir/all] Error 2
    make: *** [all] Error 2
    

    This is on Ubuntu Trusty, failing here (I am using an amalgamated version of SHA ed495edcc1bda878ef3cabd4c1ddaa1cdf2c57b0). For me, replacing isfinite() with std::isfinite() at that line let me compile. However due to the cross-platform support for isfinite here this isn't the real solution.

  •  Is there a feature to compare two different jsons and show their differences?

    Is there a feature to compare two different jsons and show their differences?

    Is your feature request related to a problem? Please describe As title. 😄

    Describe the solution you'd like Maybe construct a <method> in <class>.

    Describe alternatives you've considered The following is the implementation method and use effect that I roughly came up with: 😃

    Method prototype:

    int Json::Compare(const Json::Value compared, const Json::Value compare, Json::Value &differences);
    /*The specific implementation method can search and compare differences in the json structure tree.
    *@param: [in]<compared>	        A json that be compared.
    *        [in]<compare>		Another json that be compared.
    *	 [out]<differences>	A json shows the difference between <compared> and <compare>.
    *@return: If <compared> and <compare> are the same, return 0; 
    *	  if <compared> < <compare>, the return value is less than 0; 
    *	  if <compared> > <compare>, the return value is greater than 0.
    *	  The actual returned integer depends on the number of key-value pairs they differ from.
    */
    
  • Expose getLocationLineAndColumn() as a public API

    Expose getLocationLineAndColumn() as a public API

    Allows better use of the offset data returned by getStructuredErrors()

    Based on the work from @KyleFromKitware and comments from @BillyDonahue on #1282

  • SHARED jsoncpp ERRER

    SHARED jsoncpp ERRER

    Describe the bug I want to use SHAERD add_library to link my code file.

    This is my code add_library(${PROJECT_NAME} SHARED settingParser.cpp settingParser.h) target_link_libraries(${PROJECT_NAME} "-Wl,--whole-archive" jsoncpp "-Wl,--no-whole-archive" "-fPIC")

    ERROR is : /usr/bin/ld: /home/github/wd/littletools/3rdparty/lib/json/libjsoncpp.a(json_value.cpp.o): warning: relocation against _ZN4Json10LogicErrorD1Ev' in read-only section .text.unlikely' /usr/bin/ld: /home/github/wd/littletools/3rdparty/lib/json/libjsoncpp.a(json_reader.cpp.o): relocation R_X86_64_PC32 against symbol _ZTVN4Json17CharReaderBuilderE' can not be used when making a shared object; recompile with -fPIC /usr/bin/ld: final link failed: bad value collect2: error: ld returned 1 exit status gmake[3]: *** [settingParser/CMakeFiles/settingParser.dir/build.make:103: lib/libsettingParser.so] Error 1 gmake[2]: *** [CMakeFiles/Makefile2:439: settingParser/CMakeFiles/settingParser.dir/all] Error 2 gmake[1]: *** [CMakeFiles/Makefile2:256: CMakeFiles/trimule.dir/rule] Error 2 gmake: *** [Makefile:137: trimule] Error 2

    But when I donot use SHARED ,It works success; add_library(${PROJECT_NAME} settingParser.cpp settingParser.h) target_link_libraries(${PROJECT_NAME} "-Wl,--whole-archive" jsoncpp "-Wl,--no-whole-archive" "-fPIC")

  • CharReader: Add StructuredError

    CharReader: Add StructuredError

    The move from Json::Reader to Json::CharReader omitted the ability to get structured error messages from the parser. Clients which want to extract the line and column information have to parse the returned string. Add a new getStructuredErrors() method which exposes the error as structured data instead of a string.

    Based on the work from @kylefromkitware and comments from @BillyDonahue on #1281.

  • Negative infinity round-trips as invalid JSON

    Negative infinity round-trips as invalid JSON

    Describe the bug inf and -inf don't round trip if useSpecialFloats is false.

    To Reproduce Steps to reproduce the behavior:

    	Json::Value testJson(Json::arrayValue);
    	testJson[0] = 25.0;
    	testJson[1] = 0.0;
    	testJson[2] = -std::numeric_limits<float>::infinity();
    	Json::StreamWriterBuilder builder;
    	builder["indentation"] = "\t";
            // both false/true are incorrect
    	//builder["useSpecialFloats"] = true;
    	const std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
    	std::stringstream ss;
    	writer->write(testJson, &ss);
    	Json::Reader reader;
    	Json::Value json;
    
    	bool is_valid = reader.parse(ss, json);
    	// is_valid == false
            // errors list -1e+9999 as invalid number
    

    Expected behavior Should at least parse rather than hard fail.

    Desktop (please complete the following information):

    • OS: Windows
    • Ninja version 1.10.2
  • Passing Json::Value to a function in C++ dll is throwing read access violation exception

    Passing Json::Value to a function in C++ dll is throwing read access violation exception

    Hi , I am using JsonCPP library in my C++ project . I created a C++ dll with a function which will take Json::Value as input parameter . I have created another one exe which calls this function by passing Json::Value as argument. Inside the dll function, while reading this json value , it throws read access violation exception .

    I was passing string as well which used to give error . I changed string to char* which resolves my problem . But I don't know how to handle passing json value .

    below is the example code snippet .

    C++ dll :

    foo(json::value jsonValue)
    {
    auto value = jsonValue["name"];
    }
    

    another exe:

    I linked dll with this exe project . And while debuging I can go inside foo function . so there is no problem in loading dll and calling function .

    I am reading json from my local json file and storing it in jsonValue.

    json::value jsonValue = readFromLocalFile();
    
    cout<<jsonValue["name"];    // works well
    
    foo(jsonValue);             // goes inside foo function and breaks wile reading jsonValue["name"]
    

    I am using visual studio 2019 to build both the projects .

    image

    Can anyone please help me with this error .

Header-only library for automatic (de)serialization of C++ types to/from JSON.

fuser 1-file header-only library for automatic (de)serialization of C++ types to/from JSON. how it works The library has a predefined set of (de)seria

Jun 4, 2022
Yet another JSON/YAML/BSON serialization library for C++.
Yet another JSON/YAML/BSON serialization library for C++.

ThorsSerializer Support for Json Yaml Bson NEW Benchmark Results Conformance mac linux Performance max linux For details see: JsonBenchmark Yet anothe

Jun 15, 2022
JSON for Modern C++
JSON for Modern C++

Design goals Sponsors Integration CMake Package Managers Pkg-config Examples JSON as first-class data type Serialization / Deserialization STL-like ac

Jun 16, 2022
Parsing gigabytes of JSON per second
Parsing gigabytes of JSON per second

simdjson : Parsing gigabytes of JSON per second JSON is everywhere on the Internet. Servers spend a *lot* of time parsing it. We need a fresh approach

Jun 14, 2022
Similar to C++ streams, but the stream elements are structured JSON data rather than characters.

JIOS : JSON Input Output Streams Similar to C++ streams, but the stream elements are structured JSON data rather than characters. Contents Features [P

Aug 16, 2019
Your binary serialization library

Bitsery Header only C++ binary serialization library. It is designed around the networking requirements for real-time data delivery, especially for ga

Jun 15, 2022
Cap'n Proto serialization/RPC system - core tools and C++ library
Cap'n Proto serialization/RPC system - core tools and C++ library

Cap'n Proto is an insanely fast data interchange format and capability-based RPC system. Think JSON, except binary. Or think Protocol Buffers, except

Jun 23, 2022
A C++11 library for serialization
A C++11 library for serialization

cereal - A C++11 library for serialization cereal is a header-only C++11 serialization library. cereal takes arbitrary data types and reversibly turns

Jun 23, 2022
Header-only C++11 library to encode/decode base64, base64url, base32, base32hex and hex (a.k.a. base16) as specified in RFC 4648, plus Crockford's base32. MIT licensed with consistent, flexible API.

cppcodec Header-only C++11 library to encode/decode base64, base64url, base32, base32hex and hex (a.k.a. base16) as specified in RFC 4648, plus Crockf

Jun 8, 2022
FlatBuffers: Memory Efficient Serialization Library

FlatBuffers FlatBuffers is a cross platform serialization library architected for maximum memory efficiency. It allows you to directly access serializ

Jun 20, 2022
FlatBuffers Compiler and Library in C for C

OS-X & Ubuntu: Windows: The JSON parser may change the interface for parsing union vectors in a future release which requires code generation to match

Jun 14, 2022
Simple C++ 20 Serialization Library that works out of the box with aggregate types!

BinaryLove3 Simple C++ 20 Serialization Library that works out of the box with aggregate types! Requirements BinaryLove3 is a c++20 only library.

Dec 23, 2021
A header only C++11 library for parsing TOML

tinytoml A header only C++11 library for parsing TOML. This parser is based on TOML v0.4.0. This library is distributed under simplified BSD License.

Jun 8, 2022
cpptoml is a header-only library for parsing TOML

cpptoml A header-only library for parsing TOML configuration files. Targets: TOML v0.5.0 as of August 2018. This includes support for the new DateTime

Jun 18, 2022
Zmeya is a header-only C++11 binary serialization library designed for games and performance-critical applications

Zmeya Zmeya is a header-only C++11 binary serialization library designed for games and performance-critical applications. Zmeya is not even a serializ

Jun 6, 2022
CppSerdes is a serialization/deserialization library designed with embedded systems in mind
CppSerdes is a serialization/deserialization library designed with embedded systems in mind

A C++ serialization/deserialization library designed with embedded systems in mind

Jun 3, 2022
Morse code decoding library
Morse code decoding library

ggmorse Morse code decoding library ggmorse2.mp4 ggmorse0.mp4 ggmorse1.mp4 Try it out You can easily test the library using the free GGMorse applicati

Jun 14, 2022
C++17 library for all your binary de-/serialization needs

blobify blobify is a header-only C++17 library to handle binary de-/serialization in your project. Given a user-defined C++ struct, blobify can encode

May 29, 2022
C++ BSON Library

This is a standalone BSON ("binary JSON") library for C++. (See bsonspec.org for more information on the BSON format.) The library is at this time a b

May 11, 2022