Write and Parse JSON in C
C does not support native JSON parsers and creators. Many JSON libraries are available in C like json-c, cJSON, and much more. In this blog, we will go with cJSON to read and write JSON in C. Let's Consider the following sample JSON Document which consists of JSON Object, JSON Array, and key-value pair forms :
Setup
Click here to get the latest cJSON. Download the zip file, Once it's done we can use it as a library or include .c and .h in our project. cJSON comes with many different options which can change by passing CMAKE In source code we include some of the flags in the makefile.
Write JSON in C
STEP 1: To write JSON, First you need to include a cJSON.c and cJSON.h in your project directory. cJSON is a struct data type and working with this data type cJAON provides different functions, for example, cJSON_Create* method can be used to create respective types like Objects, arrays or references.
STEP 2: To insert key value pair, we can use cJSON_Add*ToObject methods.
STEP 3: To create JSON Array, cJSON provides cJSON_CreateIntArray(), cJSON_CreateFloatArray(), cJSON_CreateDoubleArray(), cJSON_CreateStringArray() methods. We are required to pass an array and its count correctly otherwise it will jump into out-of-bound exceptions.
STEP 4: Similarly, we can create nested JSON, with the help of cJSON_AddItemToObject function :
Let’s see a complete code of write JSON data in C :
Parse JSON in C
STEP 1: To parse JSON, we can parse JSON with cJSON_Parse() method.
STEP 2: To extract respective string objects we can use cJSON_GetObjectItem method.
STEP 3: To identify primitive data types, cJSON support cJSON_Is*() methods.
Let’s see a complete code of parse JSON data in C:
Download
cJSON library : Click here
Source Code : Click here
Credits
cJSON library - CPP JSON encoders/decoders library
json.org - Introducing JSON Standard