json++

Related tags

JSON json
Overview

JSON++

JSON++ is a self contained Flex/Bison JSON parser for C++11. It parses strings and files in JSON format, and builds an in-memory tree representing the JSON structure. JSON objects are mapped to std::maps, arrays to std::vectors, JSON native types are mapped onto C++ native types. The library also includes printing on streams. Classes exploit move semantics to avoid copying parsed structures around. It doesn't require any additional library (not even libfl).

Updates

July 20, 2014 - In the past few months I have merged various pull requests, which I considered good additions to the code (e.g., someone fixed memory leaks, someone improved the CMake build system, someone started to add support for unicode escaped characters). These were all very good contributions, and I'd like to thank anyone that has filed a pull request for JSON++. However, I have sometimes overlooked the code that I was merging and, sometimes, pull requests with early code were merged in the main distribution. For this reason, a few days ago I have rolled back to a previous version of the code, from the end of June. This is my first open source projects that gains a bit of traction (the repository has about 1500 visits per month), and I'll be more careful in merging pull requests from now on.

Git repository

A version of this repository (regularly mirrored) is available on GitHub.

Contributors

JSON++ is not a personal project anymore, people is constantly writing to me, and sending pull requests to improve it and make it better. I'd like to thank these people by adding them to this Contributors section (in order of contribution).

Thanks for your effort fellas.

Usage

#include <iostream>
#include "json.hh"

using namespace std;
using namespace JSON;

int main(int argc, char** argv)
{
	// Read JSON from a string
	Value v = parse_string(<your_json_string>);
	cout << v << endl;
    
    // Read JSON from a file
	v = parse_file("<your_json_file>.json");
	cout << v << endl;
	
    // Or build the object manually
    Object obj;

    obj["foo"] = true;
    obj["bar"] = 3;

    Object o;
    o["given_name"] = "John";
    o["family_name"] = "Boags";

    obj["baz"] = o;
    
    Array a;
    a.push_back(true);
    a.push_back("asia");
    a.push_back("europe");
    a.push_back(55);

    obj["test"] = a;
    
	cout << o << endl;
    
    return 0;
}

How to build JSON++

The project includes a CMakeLists.txt files which allows you to generate build files for most build systems. Just run

cmake .    

and then

make

The project generates

  • json.tab.hh,
  • json.tab.cc, and
  • lex.yy.cc

files from json.l and json.y, then compiles them (and a few other files) into a libjson library, which is finally used to link the test executable. You can use the library in your projects, or use the Flex/Bison files straight away.

How to build with unit tests

If you have the cppunit framework (http://sourceforge.net/projects/cppunit/) installed on your system, you can make a build with unit tests as follows:

mkdir build
cd build
cmake .. -DWITH_UNIT_TESTS=ON
make
ctest -V

The usage of an out of source build is strongly advised, since even more files are generated by the CTest testing tool.

How to build for measuring code coverage

Specify the Coverage build type as follows:

cd build
cmake .. -DCMAKE_BUILD_TYPE=Coverage

You can get a code coverage report with gcovr (http://gcovr.com):

cd build
gcovr --xml --root .. --exclude "ut/.*" --exclude "test.cc" > coverage.xml

This produces a report in the XML file format, which can be visualized with tools such as the Cobertura plugin for the jenkins continuous integration server.

How to generate API documentation

If you have doxygen (http://www.stack.nl/~dimitri/doxygen/) installed on your system, an API documentation will be generated automatically as part of make. You can also request its generation explicitly:

make doc

You will find the documentation in your build directory at ./html/index.html.

Flex/Bison quirks when using C++ classes

This section is for the ones who got here because they're trying to build stuff with Flex/Bison and C++. This was my first Flex/Bison parser (the main motivation behind its development being that I didn't find a parser for JSON in C++ which didn't require a number of extra libraries, plus I wanted to learn Flex/Bison).

So, for the ones venturing in this world, here's a few things I wish I knew when I set off to write the parser.

  1. Every rule of the Bison grammar has a left-hand side, to which the parsed objects (no matter their type), must be assigned. To do this, a union is used. Bison uses the %union { ... } rule to declare the types inside the union, which must only contain native C types or pointers to C++ classes,
  2. in case pointers to C++ classes are used in %union, classes extending std containers won't work, so you'll need to wrap std stuff in your own classes,
  3. always put a starting rule in the grammar to assign the result of the overall parse to a variable, e.g., json: value { $$ = $1; },
  4. as a general rule, functions requiring Flex functions, e.g., yy_scan_string, etc., should be defined in the .l file, and their prototypes put in the .y file as well, so that they can be called from the parser's functions,
  5. ... (to be continued as I find out more).

Licensing

This code is distributed under the very permissive MIT License but, if you use it, you might consider referring to the repository.

Comments
  • Pedantic warn level and CMAKE_CXX_FLAGS preservation

    Pedantic warn level and CMAKE_CXX_FLAGS preservation

    Using a parent cmake project with high warning levels such as "-Werror -Wall -Wextra -pedantic" could not compile when including this json library as sub project. Additionally, 32 bit projects could not link to the library because compiler flags like "-m32" were overwritten. This pull request fixes both issues.

    opened by magnus-lutz 2
  • buffer overflow while testing

    buffer overflow while testing

    I run test.cc and get the following message... Should I write something like "delete A" at somewhere?

    ==26390==ERROR: AddressSanitizer: global-buffer-overflow on address 0x0000014758c0 at pc 0x00000053d276 bp 0x7ffe260b12f0 sp 0x7ffe260b12e8 READ of size 8 at 0x0000014758c0 thread T0 #0 0x53d275 in yyparse() /opt/json/json.y:87:50 #1 0x53efb3 in parse_file(char const*) /opt/json/json.y:171:18 #2 0x51b058 in main /opt/json/test.cc:11:15 #3 0x7f842d19db96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310 #4 0x41e519 in _start (/opt/json/test+0x41e519)

    0x0000014758c4 is located 0 bytes to the right of global variable 'yyleng' defined in '/opt/json/lex.yy.cc:290:5' (0x14758c0) of size 4 SUMMARY: AddressSanitizer: global-buffer-overflow /opt/json/json.y:87:50 in yyparse() Shadow bytes around the buggy address: 0x000080286ac0: 00 00 00 00 00 00 00 00 00 00 00 00 01 f9 f9 f9 0x000080286ad0: f9 f9 f9 f9 00 00 00 00 01 f9 f9 f9 f9 f9 f9 f9 0x000080286ae0: 04 f9 f9 f9 f9 f9 f9 f9 00 00 00 00 00 f9 f9 f9 0x000080286af0: f9 f9 f9 f9 04 f9 f9 f9 f9 f9 f9 f9 00 00 f9 f9 0x000080286b00: f9 f9 f9 f9 04 f9 f9 f9 f9 f9 f9 f9 01 f9 f9 f9 =>0x000080286b10: f9 f9 f9 f9 00 00 00 00[04]f9 f9 f9 f9 f9 f9 f9 0x000080286b20: 00 f9 f9 f9 f9 f9 f9 f9 00 f9 f9 f9 f9 f9 f9 f9 0x000080286b30: 04 f9 f9 f9 f9 f9 f9 f9 00 f9 f9 f9 f9 f9 f9 f9 0x000080286b40: 01 f9 f9 f9 f9 f9 f9 f9 01 f9 f9 f9 f9 f9 f9 f9 0x000080286b50: 01 f9 f9 f9 f9 f9 f9 f9 00 f9 f9 f9 f9 f9 f9 f9 0x000080286b60: 00 f9 f9 f9 f9 f9 f9 f9 00 f9 f9 f9 f9 f9 f9 f9 Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Freed heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 Container overflow: fc Array cookie: ac Intra object redzone: bb ASan internal: fe Left alloca redzone: ca Right alloca redzone: cb ==26390==ABORTING

    opened by frokaikan 1
  • Compilation error due to warning

    Compilation error due to warning

    I tried to build it on OS X El Capitan but failed. I installed an updated Bison via brew. CMake:

    -- The CXX compiler identification is AppleClang 7.0.0.7000072
    ...
    -- Found BISON: /usr/local/bin/bison (found suitable version "3.0.4", minimum required is "2.4") 
    -- Found FLEX: /usr/bin/flex (found suitable version "2.5.35", minimum required is "2.5") 
    

    make:

    .../lex.yy.cc:1213:16: error: function 'yyinput' is not needed and will not be emitted [-Werror,-Wunneeded-internal-declaration]
        static int yyinput (void)
    

    It seems just a warning for an unused static function. Besides, I failed building it on a clean Ubuntu also. There are lots of messages. Do you want me to paste them as another issue as well?

    opened by miloyip 1
  • add to string function to class Object and Array,let them can be convert...

    add to string function to class Object and Array,let them can be convert...

    ... to std::string object without tabs and newline. so,the demo test.cc may have this output:{"bar":3,"baz":{"failure":true,"success":"no way"},"beer":[true,"asia","europa",55,3.120000,3.120000],"foo":true} when you want to use json++ to get a data buf to send,it may be useful.^_^

    opened by mobilefzb 0
  • "json.tab.hh not found"

    I just downloaded the repo. I tried to compile test.cc, and the fatal error message is:

    'In file included from /Users/Chadtech/Documents/code/json-master/test.cc:2: /Users/Chadtech/Documents/code/json-master/./json.hh:5:10: fatal error: 'json.tab.hh' file not found

    include "json.tab.hh" // parser'

    opened by Chadtech 3
  • float casting when decimal part is 0

    float casting when decimal part is 0

    When saving a float to an object if the decimal part is 0 then the object is outputed as an int, and therefore reimported wrongly, here's an example:

    //Creating the object
    Object obj;
    float value = 10;
    obj["value"] = value;
    //Saving to a string
    std::ostringstream stream;
    stream << obj;
    std::string objString =  stream.str();
    std::cout << "String:" << objString << std::endl;
    //Reading that string
    Value v2 = parse_string(objString);
    float value2 = v2["value"].as_float();
    std::cout << value2 << std::endl;
    

    which outputs:

    String:{
            "value": 10
    }
    0
    

    A solution that I found was to change the case for FLOAT in the function ostream& operator<<(ostream& os, const Value& v) in file json_st.cc to:

     value = (long double)v;
          if(value - (int) value == 0.0){
            os.precision(1);
            os.setf( std::ios::fixed );
          }
                os << value;
    

    So now the output of the previous program is:

    String:{
            "value": 10.0
    }
    10
    

    I'm not sure if this is the best solution because it envolves declaring a long double value outside the switch, but at least it is working for me.

    opened by Nibodhika 1
Owner
Tommaso Urli
Tommaso Urli
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
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. 108 Aug 26, 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 16 May 10, 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 28 Sep 14, 2022
Ultralightweight JSON parser in ANSI C

cJSON Ultralightweight JSON parser in ANSI C. Table of contents License Usage Welcome to cJSON Building Copying the source CMake Makefile Vcpkg Includ

Dave Gamble 8k Sep 29, 2022
JSON parser and generator for C/C++ with scanf/printf like interface. Targeting embedded systems.

JSON parser and emitter for C/C++ Features ISO C and ISO C++ compliant portable code Very small footprint No dependencies json_scanf() scans a string

Cesanta Software 622 Sep 24, 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 Sep 26, 2022
JSON & BSON parser/writer

jbson is a library for building & iterating BSON data, and JSON documents in C++14. \tableofcontents Features # {#features} Header only. Boost license

Chris Manning 40 Sep 14, 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
Jsmn is a world fastest JSON parser/tokenizer. This is the official repo replacing the old one at Bitbucket

JSMN jsmn (pronounced like 'jasmine') is a minimalistic JSON parser in C. It can be easily integrated into resource-limited or embedded projects. You

Serge Zaitsev 3.1k Oct 3, 2022
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

Niels Lohmann 32k Oct 2, 2022
A JSON parser in C++

JSON++ Introduction JSON++ is a light-weight JSON parser, writer and reader written in C++. JSON++ can also convert JSON documents into lossless XML d

Hong Jiang 488 Sep 13, 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 513 Sep 24, 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.7k Oct 5, 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 Sep 22, 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.4k Sep 30, 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
Very simple C++ JSON Parser

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

Amir Saboury 65 Sep 28, 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 262 Sep 29, 2022