Skip to content
Jonas Andersson edited this page Mar 21, 2018 · 4 revisions

jWrite

Credit to Tony Wilk

Orginal publish jWrite-a-really-simple-JSON-writer-in-C

Introduction

jWrite is a simple way of writing JSON to a char buffer in C, directly from native variables. It manages the output buffer so you don't overrun, it handles all the fiddly quotes, brackets and commas and reports where you have tried to create invalid JSON. There is now a C++ version with demo sketch for Arduino.

You can, of course, write json to a string with sprintf()... but this is miles better.

Background

This is a companion set of functions to "jRead an in-place JSON element reader" (http://www.codeproject.com/Articles/885389/jRead-an-in-place-JSON-element-reader).

The same basic design principles apply: it should be in straight C, have little or no memory overhead, execute fast and be simple to use. It is intended for use in embedded projects where using some nice and big C++ structured solution is just not appropriate.

Several approaches were considered; the 'most automatic' was to define a structure which described the JSON and contained pointers to external variables to get the data - this seemed a good idea since it would then be a single call to 'stringify' everything... the downside was the complexity of API required to define such a structure and keep it all in memory.

For the programmer, it is pointless to make configuration of a JSON writer more complicated than writing the stuff out by hand!

jWrite attempts a happy medium in that it is simple and doesn't seem to do much - you just tell it what to write and it does it.

Using the Code

Jumping straight in:

jwOpen( buffer, buflen, JW_OBJECT, JW_PRETTY );  // open root node as object
jwObj_string( "key", "value" );                  // writes "key":"value"
jwObj_int( "int", 1 );                           // writes "int":1
jwObj_array( "anArray");                         // start "anArray": [...] 
    jwArr_int( 0 );                              // add a few integers to the array
    jwArr_int( 1 );
    jwArr_int( 2 );
jwEnd();                                         // end the array
err= jwClose();                                  // close root object - done

which results in:

{
    "key": "value",
    "int": 1,
    "anArray": [
        0,
        1,
        2
    ]
}

The output is prettyfied (it's an option) and has all the { } [ ] , : " characters in the right place.

Although this looks very straightforward, not a lot different than a load of sprintf()s you may say, but jWrite does a few really useful things: it helps you make the output valid JSON.

You can easily call a sequence of jWrite functions which are invalid, like:

Clone this wiki locally