So you want to parse JSON with C? Welcome aboard!

First get json-c, configure, compile, and update your ld cache
tar xf json-c-0.9.tar.gz
cd json-c-0.9
./configure && make && sudo make install
sudo ldconfig

Now use one of the test files provided or this example:
cd ..
vim json-example.c
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#include "json.h"

int main(int argc, char **argv)
struct json_object *new_obj;

// I added some new lines... not in real program
new_obj = json_tokener_parse("/* more difficult test case */ { \"glossary\": { \"title\": \"example glossary\", \"pageCount\": 100, \"GlossDiv\": { \"title\": \"S\", \"GlossList\": [ { \"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\", \"markup\"] } ] } } }");
printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));

new_obj = json_object_object_get(new_obj, "glossary");
printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));

new_obj = json_object_object_get(new_obj, "pageCount");

int pageCount = json_object_get_int(new_obj);

printf("Page count = %d", pageCount);


return 0;

Put it in a Makefile with the right settings.
vim Makefile
all: static

gcc -static json-example.c -L/usr/local/lib -ljson -I/usr/local/include/json -o json-example-static

gcc json-example.c -L/usr/local/lib -ljson -I/usr/local/include/json -o json-example-shared

.PHONY: all static shared

Finally test that it works:
make static
make shared

Hopefully that's enough to get you started. The big thing is that when you compile your own projects, make sure that you include the json library and paths.
how to manage memory with json-c, i have tried it on iphone and instruments show it is leaking all over the place?


By AJ ONeal

If you loved this and want more like it, sign up!

Did I make your day?
Buy me a coffeeBuy me a coffee  

(you can learn about the bigger picture I'm working towards on my patreon page )