git clone https://github.com/DaveGamble/cJSON.git
cd cJSON/
mkdir build
cd build/
cmake ..
sudo make install
cd ..
sudo ln -s /usr/local/lib/libcjson.so /usr/lib/libcjson.so
sudo ln -s /usr/local/lib/libcjson.so.1 /usr/lib/libcjson.so.1
sudo ln -s /usr/local/lib/libcjson.so.1.7.12 /usr/lib/libcjson.so.1.7.12
gcc cJSONTestProgram.c -l cjson
./a.out
Planet:
Mars, 6.39e+23 kgs
Moon:
Phobos, 70 kms
Moon:
Deimos, 39 kms
satheesh@skyrdkdev:~/cJSON$ cat cJSONTestProgram.c
//src: https://spacesciencesoftware.wordpress.com/2013/09/10/a-good-way-to-read-json-with-c/
#include stdio.h
#include string.h
#include cjson/cJSON.h
int main(int argc, const char * argv[]) {
/*{
"name": "Mars",
"mass": 639e21,
"moons": [
{
"name": "Phobos",
"size": 70
},
{
"name": "Deimos",
"size": 39
}
]
}*/
char *strJson = "{\"name\" : \"Mars\",\"mass\":639e21,\"moons\":
[{\"name\":\"Phobos\",\"size\":70},{\"name\":\"Deimos\",\"size\":39}]}";
printf("Planet:\n");
// First, parse the whole thing
cJSON *root = cJSON_Parse(strJson);
// Let's get some values
char *name = cJSON_GetObjectItem(root, "name")->valuestring;
double mass = cJSON_GetObjectItem(root, "mass")->valuedouble;
printf("%s, %.2e kgs\n", name, mass);
// Note the format! %.2e will print a number with scientific notation and 2 decimals
// Now let's iterate through the moons array
cJSON *moons = cJSON_GetObjectItem(root, "moons");
// Get the count
int moons_count = cJSON_GetArraySize(moons);
int i;
for (i = 0; i < moons_count; i++) {
printf("Moon:\n");
// Get the JSON element and then get the values as before
cJSON *moon = cJSON_GetArrayItem(moons, i);
char *name = cJSON_GetObjectItem(moon, "name")->valuestring;
int size = cJSON_GetObjectItem(moon, "size")->valueint;
printf("%s, %d kms\n", name, size);
}
// Finally remember to free the memory!
cJSON_Delete(root);
return 0;
}
satheesh@skyrdkdev:~/cJSON$
No comments:
Post a Comment