JSON-C Tutorial: How to Parse JSON in C

  Programming

JSON, short for JavaScript Object Notation, is so ubiquitous these days! However, most people seem to use it only with Python, JavaScript, and other such very modern languages. Not many know how to work with it in C, one of the first high-level programming languages ever created. Because C is such an old language–46 years at the time of this writing–it doesn’t have any built-in support for JSON. Fortunately, there are many JSON libraries for C, and json-c is one of them. In this video tutorial, I show how to write C code, one that’s compatible with the original ANSI C standard, to parse a simple JSON document.

If you liked the video, please give it a thumbs up and subscribe to the channel. Thank you!

Here’s the complete source code:

#include<stdio.h>
#include<json-c/json.h>

int main(int argc, char **argv) {
	FILE *fp;
	char buffer[1024];
	struct json_object *parsed_json;
	struct json_object *name;
	struct json_object *age;
	struct json_object *friends;
	struct json_object *friend;
	size_t n_friends;

	size_t i;	

	fp = fopen("test.json","r");
	fread(buffer, 1024, 1, fp);
	fclose(fp);

	parsed_json = json_tokener_parse(buffer);

	json_object_object_get_ex(parsed_json, "name", &name);
	json_object_object_get_ex(parsed_json, "age", &age);
	json_object_object_get_ex(parsed_json, "friends", &friends);

	printf("Name: %s\n", json_object_get_string(name));
	printf("Age: %d\n", json_object_get_int(age));

	n_friends = json_object_array_length(friends);
	printf("Found %lu friends\n",n_friends);

	for(i=0;i<n_friends;i++) {
		friend = json_object_array_get_idx(friends, i);
		printf("%lu. %s\n",i+1,json_object_get_string(friend));
	}	
}

If you like creating art, and are familiar with JavaScript, do take a look at my classes on Skillshare. It really helps me keep this site up.

Emergent art
Julia Set
Peter de Jong attractor

If you found this article useful, please share it with your friends and colleagues!