Please help Ukrainian armed forces! Official Fundraising

cJSON: Lightweight JSON parser

1 1 1 1 1 cJSON: Lightweight JSON parser5.00Rating 5.00 (518 Votes)

If you are searching for cJSON usage samples, or example code that you can just copy-paste into your C project, you came to the right place. 

cJSON is one of the simple JSON parser that you can get your job done with. It's a single file of C, and a single header file.

JSON is described best here: http://www.json.org/ It's like XML, but fat-free. You use it to move data around, store things, or just generally represent your program's state.

As a library, cJSON exists to take away as much legwork as it can, but not get in your way. 

There are several ways to incorporate cJSON into your project, one of them is just copying the source.

Because the entire library is only one C file and one header file, you can just copy cJSON.h and cJSON.c to your projects source and start using it.

cJSON is written in ANSI C (C89) in order to support as many platforms and compilers as possible.

Some JSON:

{
"name": "Jack (\"Bee\") Nimble",
"format": {
"type": "rect",
"width": 1920,
"height": 1080,
"interlace": false,
"frame rate": 24
}

Assume that you got this from a file, a webserver, or magic JSON elves, whatever, you have a char * to it. Everything is a cJSON struct. Get it parsed:

cJSON * root = cJSON_Parse(my_json_string);


This is an object. We're in C. We don't have objects. But we do have structs. What's the framerate?

cJSON *format = cJSON_GetObjectItemCaseSensitive(root, "format");
cJSON *framerate_item = cJSON_GetObjectItemCaseSensitive(format, "frame rate");
double framerate = 0;
if (cJSON_IsNumber(framerate_item))
{
    framerate = framerate_item->valuedouble;
}


Want to change the framerate?

cJSON *framerate_item = cJSON_GetObjectItemCaseSensitive(format, "frame rate");
cJSON_SetNumberValue(framerate_item, 25);


Back to disk?

char *rendered = cJSON_Print(root);

Finished? Delete the root (this takes care of everything else).

cJSON_Delete(root);


That's AUTO mode. If you're going to use Auto mode, you really ought to check pointers before you dereference them. If you want to see how you'd build this struct in code?

cJSON *root;
cJSON *fmt;
root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject());
cJSON_AddStringToObject(fmt, "type", "rect");
cJSON_AddNumberToObject(fmt, "width", 1920);
cJSON_AddNumberToObject(fmt, "height", 1080);
cJSON_AddFalseToObject (fmt, "interlace");
cJSON_AddNumberToObject(fmt, "frame rate", 24);

 

 

Source: https://github.com/DaveGamble/cJSON

 

You have no rights to post comments

Monday the 11th.