Month: November 2019

C library for JSON/JSON5 parsing and writing

I have recently been using JSON in various projects and quite like the format. It is very easy to use in Python and is one of the standard libraries that ship with Python. I decided I wanted to use JSON as configuration files in some of my C projects. Previously I have used XML for configuration and have some convenient libraries for marshalling and unmarshalling the data in an XML file to C structures. I wanted to write a library that would let me swap over to using JSON files without adding complexity to those projects.

In particular I want to be able to have a C structure that contains configuration information and be able to save it to JSON and read it back out without much work. In Python this is very easy as a lot of python objects can just be written to JSON with a single function. As C doesn’t have anyway of inspecting its own C structure there needs to be some mapping provided.

So over the past few months I’ve worked on creating “JsonLib“. This is a C library that can marshall and unmarshall data to and from JSON. Originally I was just going to write a JSON parser with an extension to allow comments (because having comments is very convenient in configuration files). While looking up what the most standard extensions were for handling comments I came across JSON5. I decided to make my library JSON5 compliant rather than simply JSON with non official extensions.

By default JsonLib will accept and parse JSON5, however it has a mode which will only accept strict JSON if desired. In general, unless you are writing something to validate JSON, it is better to always accept JSON5 as input. For output the library defaults to strict JSON unless JSON5 is explicity enabled. This provdes greatest compatibility. By default it can parse anything and for output it always makes strict JSON which anything else will be able to read. It should be noted that JSON5 is a strict superset of JSON. So not enabling JSON5 simply means rejecting input that otherwise could unambiguously be parsed.

The library is now available on GitHub

This is free and unencumbered software released into the public domain.

Documentation is rather sparse at the moment, but I wanted to release it anyway. Hopefully there is enough examples in the unit tests to demonstrate its use.

This a link to the current user guide