Wednesday, November 18, 2015

Parsing JSON in C with json-c

Recently I ran into a case where I needed to parse some JSON responses in C. I didn't really feel like writing my own parser, so I turned to the internet. A quick Google search turned up some good candidates including jsmn, jansson, and json-c. As the environment I work in is a Redhat derivative and the response I needed parse was rather simple, I opted to use json-c as it was in the EPEL repository.

The thing I quickly realized about json-c is that it's poorly documented and there are a scattered bunch of examples out there, half of which were for C++. I did eventually find their doxygen reference which helped me piece some of how it works together. After some poking around and looking at some of the examples available out there, I came up with the following code to do some testing:

#include <stdio.h>
#include <string.h>
#include <json/json.h>

int main(void) {
 struct json_object *jobj = NULL;
 enum json_tokener_erro jerr = 0;
 char str[256] = "";
 
 sprintf(str, "{\"Name\": \"Jacob\", \"Age\": 28, \"Gender\": \"Male\"}");
 
 jobj = json_tokener_parse_verbose(str, &jerr);
 if(jerr = json_tokener_success) {
  json_object_object_foreach {
   printf("%s: %s\n", key, json_object_get_string(val));
  }
 }
 
 printf("Error Code: %d\n", jerr);
 
 return EXIT_SUCCESS;
}

The above code snippet gave me the following:

Name: Jacob
Age: 28
Gender: Male
Error Res: 0

I'd like note that the error code of 0 is the equivalent of 'json_tokener_success.' Obviously this does not cover all cases on how to handle things with json-c, but I wanted people to have a good starting place to go from.