a JSON parser and printer library in C. easy to integrate with any model.

Related tags

JSON libjson

libjson - simple and efficient json parser and printer in C


libjson is a simple library without any dependancies to parse and pretty print the JSON format (RFC 4627). The JSON format is a concise and structured data format.


  • interruptible parser: append data to the state how you want it.
  • No object model integrated
  • Small codebase: handcoded parser and efficient factorisation make the code smalls and perfect for embedding.
  • Fast: use efficient code and small parsing tables for maximum efficiency.
  • Full JSON support.
  • UTF8 validation of the input.
  • No number conversion: user convert data the way they want.
  • Secure: optional limits on nesting level, and on data size.
  • Optional comments: in YAML/python style and C style.
  • Optional user defined allocation functions.

libjson parser is an interruptible handcoded state parse. the parser takes character or string as input. Since it's interruptible, it's up to the user to feed the stream to the parser, which permits complete flexibility as to whether the data is coming from a pipe, a network socket, a file on disk, a serial line, or crafted by the user.

The parser doesn't create an object tree for you, but each time it comes up with an element in this data, it just callback to the user with the type found and for some type, the data associated with it. It can be compared to the SAX way of XML, hence it's called SAJ (Simple API for JSon).

The parser doesn't convert number to any native C format, but instead callback with a string that is a valid JSon number. JSon number can be of any size, so that's up to user to decide whetever or not, the number can map to native C type int32_t, int64_t, or a complex integer type. As well the user has a choice to refuse the integer at the callback stage if the length is not appropriate.

The parser optionally allows YAML and/or C comments to be ignored if the config structure is set accordingly, otherwise a JSON_ERROR_COMMENT_NOT_ALLOWED is returned.

Embedding & Build system

The primary use case of this pieces of code is providing JSON capability to your program or library, without adding an extra build dependency. You can add it to your project directly, and integrate it without any fuss.

The "build system" available with the library is just a way to test that everything in the library conforms to specifications and features. It's not necessarily intended as a way to build portable dynamic library (.so or .dll). It should works in simple case of building on Linux and BSDs though.

For others use (eg. windows, OS X, obscure unixes), it is much simpler to integrate the library in your program or library directly.

Simple build fixes to build on more platforms will be accepted though.


Open a pull request with your new feature, simple code fix, or documentation fixes. Please conform to coding style, and to the spirit of the library: policy is not imposed by the library.

The Parser API

The parser API is really simple, totaling only 5 API calls:

  • json_parser_init
  • json_parser_char
  • json_parser_string
  • json_parser_is_done
  • json_parser_free

json_parser_init initializes a new parser context from a parser config and takes a callback + userdata. This callback function is used everything the parser need to communicate a type and value to the client side of the library.

json_parser_char take one character and inject it in the parser. on parsing success it will return a 0 value, but on parsing error it returns a parsing error that represents the type of the error encounters. see JSON_ERROR_* for the full set of return values.

json_parser_string is similar to json_parser_char except that it takes a string and a length. it also returns the number of character processed, which is useful when an parser error happened in the stream to pinpoint where.

json_parser_is_done permits to test whetever or not the parser is in a terminated state. it involves not beeing into any structure.

json_parser_free is the opposite of init, it just free the allocated structure.

The Printer API

the printer API is simple too:

  • json_printer_init
  • json_printer_free
  • json_printer_pretty
  • json_printer_raw

json_printer_init initialise a printing context and takes a callback + userdata that will be called for every character that the printer wants to output. the caller can have the printer callback redirect to anything it wants.

json_printer_free is the opposite of init

json_printer_raw takes a json type and an optional data and length value depending on the type. it's up to the caller to verify that the order of type are JSON-compliant, otherwise the generated document won't be able to be parsed again.

json_printer_pretty works like json_printer_raw but is targetted for human reading by appending newlines and spaces

Jsonlint utility program

jsonlint utility provided with the library to verify, or reformat json stream. also useful as example on how to use the library.

  • New data type JSON_BSTRING for binary strings

    New data type JSON_BSTRING for binary strings

    This string output type replaces all non printable bytes (00-07, 0b, 0e-1f, 7f-ff) to "\u00xx" sequences. This allows json decoders to reconstruct binary string without interpreting binary sequences as Unicode characters.

    opened by fln 3
  • not possible to have values on top level

    not possible to have values on top level

    See test cases at:


    This works fine in both Chrome and Python, and should probably be supported for completeness sake.

    opened by dsvensson 3
  • do_action(...) can return an uninitialized value, resulting in wrong behaviour

    do_action(...) can return an uninitialized value, resulting in wrong behaviour

    Given the input {"t":true,, the parser (json_parser_string(...)) would tell me that an error had occurred and give me the invalid error code 32767. Initializing int ret to zero in do_action(...) seems to fix the problem.

    opened by maghoff 3
  • more easy and API for json-dom.(zhaozg fork)

    more easy and API for json-dom.(zhaozg fork)

    HI, Small, clever, good performace, event driven, and I like it. json string to struct is good, so i do some work to enhance c struct to json string.

    I fork at https://github.com/zhaozg/libjson, add jsondom.c and jsondom.h code, some hack on json-dom api. Hope this will make you think about a more easy way for construct json-dom from c api. Thanks.

    opened by zhaozg 2
  • Output doesn't pass JSONLint and doesn't parse with Node.js

    Output doesn't pass JSONLint and doesn't parse with Node.js

    MediaTags uses libjson for converting id3tags to JSON.

    However, the output isn't parseable and doesn't pass JSONLint.com

    See gist: https://gist.github.com/733715

    opened by coolaj86 2
  • Designated array initializers are not supported in MSVC and causes the build to fail

    Designated array initializers are not supported in MSVC and causes the build to fail

    (Continuing the discussion from issue #3)

    which part of the actions_map table MSVC is complaining about ? is it the function pointer or the array initilizer that it thinks is non-constant ?

    I'm not entirely sure that I've got the terminology exactly right, but MSVC does not implement what I think might be called designated array initializers:

    int a[3] = {
        [1] = 5,
        [0] = 7

    The [1] =-part throws MSVC completely off. This seems incredible, since this syntax is a part of C99, but MSVC does not claim to implement C99 :(

    Currently, they are trying to implement C++0x, and anything from C99 that's included in C++0x will be ported to the C-compiler. Unfortunately this syntax has not been included and is not on the roadmap for MSVC.

    I'd be happy to help getting libjson working on MSVC, but I'm not entirely sure what might be the best solution for this exact problem. Any thoughts?

    opened by maghoff 2
  • License not defined for this project

    License not defined for this project

    Hi, I want to reuse your likely open-source json parser in the my closed-souce program. I wanted to check whether your license allows me to do that but suddenly found out there's no any license at all. Please indicate which license is applicable. If you are not aware baout details of the open-sorce licenses, you probably need to read here more - https://opensource.org/licenses I recommed new BSD 3-clause license or MIT licsnse - this allows code to be compiled into program statically, on the constast LGPL allows only dynamic linking of the closed-source and open-souce code. Please indicate your choise of license by addin file with license text to repository. Thank you in advance...

    opened by IvanPizhenko 1
  • Some minor fixes

    Some minor fixes

    The two first patches fix a non-logical thing : casting an unsigned as a signed to compare it with unsigned. The third one is more a warning fix : as the 'printer' parameter is unused. Then I chose to reset it. The last one is to remove an unused trailing white space (you can ignore this one).

    opened by NicolasDP 1
  • Small fix relating to compiler warnings.

    Small fix relating to compiler warnings.

    Hi Vincent,

    I ended up compiling your json.c & json.h files using the Sun Studio compiler - which threw up warnings about having '-1' as an unsigned 8bit int in the hextable.

    Simple fix is to convert all the -1's to 255 (0xFF) within the hextable (as that's what GCC treats them as anyway).

    That's it, no other warnings or errors were generated.



    opened by iainb 1
  • Some MSVC-fixes

    Some MSVC-fixes

    Unfortunately, libjson does not compile with MS's C compiler :(

    These commits fix some of the problems. Some of the changes, for example relating to signed vs unsigned, make sense independently of MSVC, I think.

    With all these changes, it still won't work in MSVC, because it does not implement support for designated initializers for arrays :( This does not seem to be on the roadmap for MSVC either, unfortunately.

    Even though it still won't work in MSVC, I find it valuable to deviate as little as possible from what works on the greatest amount of compilers. Pull what you feel like, and disregard the rest, no stress :)

    If the actions_map could easily be initialized in an MSVC-friendly way, I would be very grateful. I'm a bit scared of that table myself, so I don't know quite where to start if I were to change it :) I've implemented initializing it at runtime as a test, and with that final change it works nicely in MSVC.

    opened by maghoff 1
  • Fix memory reallocation bug

    Fix memory reallocation bug

    A bug in memory reallocation caused stack growth past the initial size to result in a heap buffer overflow. This changes the memory_realloc call in dom_push to allocate newsize elements instead of newsize bytes.

    This appears to fix issue #20.

    opened by Cebtenzzre 0
  • Improve error reporting

    Improve error reporting

    Thanks for the library. I'm now using it to load and save configuration files in an IoT Linux service.

    I have made some small additions I think you will find useful (feel free to disregard if not!):

    1. Add function json_strerror. Takes an int return value from any other function in the library and returns a const char* of the human-readable error message for that code (or '<unknown>' if it isn't a known error code).
    2. Add function json_perror. Calls json_strerror and outputs the message to stderr.

    All of my changes can be disabled by uncommenting the #define JSON_NO_ERRORMSG line I added to json.h. I did this in case memory constraints are a concern.

    These functions are intended to be in the spirit of the POSIX strerror and perror functions.

    Cheers, Ryan

    opened by ryanlederman 4
  • In-place parsing mode and unit-tests

    In-place parsing mode and unit-tests

    I added the following features to the library (mostly related to event based parsing mode) and since they are backward compatible with the current library API I thought it might be a good idea to merge them into upstream:

    • In-place parsing mode: memory utilization required by the library does not depend anymore on the input sequence. The input buffer is leveraged to execute in-place parsing and no extra memory is allocated for this.
    • Partial data callbacks: this is more like a requirement needed to implement in-place parsing mode. When this is enabled, the parser doesn't keep any internal buffer across two consecutive invocations of the parser function.
    • Support for Catch framework and unit-tests: added unit tests by using Catch test framework
    • Very small refactoring.

    To Do:

    • Documentation needs to be updated in case you decide to merge these features.

    Cheers, Francesco

    opened by demartinofra 0
  • -Wsign-compare warnings

    -Wsign-compare warnings


    I get the following warnings when compiling with -Wsign-compare:

    json.c: In function ‘json_print_args’:
    json.c:965:15: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
        if (length == -1)
    jsonlint.c: In function ‘printchannel’:
    jsonlint.c:48:10: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
      if (ret != length)
    jsonlint.c: In function ‘process_file’:
    jsonlint.c:96:17: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
       for (i = 0; i < processed; i++) {
    opened by edmonds 2
  • Segmentation fault

    Segmentation fault

    Hi there

    I fuzzed libjson with American Fuzzy Lop (http://lcamtuf.coredump.cx/afl/ , for no real reason at all, I was just looking for libraries to test AFL). I was running jsonlint with:

    jsonlint --tree inputfile

    The inputfile with the following content will crash jsonlint (segmentation fault):

    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[][[[[[[[[[[[[[[

    Best regards, floyd

    opened by floyd-fuh 3
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
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
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
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
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 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 637 Dec 30, 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
RapidJSON is a JSON parser and generator for C++.

A fast JSON parser/generator for C++ with both SAX/DOM style API

Tencent 12.6k Dec 30, 2022
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
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 8.3k Jan 4, 2023
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
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.2k Jan 9, 2023
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 498 Dec 28, 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
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
A fast JSON parser/generator for C++ with both SAX/DOM style API

A fast JSON parser/generator for C++ with both SAX/DOM style API Tencent is pleased to support the open source community by making RapidJSON available

Tencent 12.6k Dec 30, 2022
Lightweight, extremely high-performance JSON parser for C++11

sajson sajson is an extremely high-performance, in-place, DOM-style JSON parser written in C++. Originally, sajson meant Single Allocation JSON, but i

Chad Austin 546 Dec 16, 2022
🔋 In-place lightweight JSON parser

?? JSON parser for C This is very simple and very powerful JSON parser. It creates DOM-like data structure and allows to iterate and process JSON obje

Recep Aslantas 23 Dec 10, 2022