Hello I have never used json-c before and im trying to Parse this json file:
{
"result": {
"schedules": [
{
"message": "2 mn",
"destination": "La Defense (Grande Arche)"
},
{
"message": "6 mn",
"destination": "La Defense (Grande Arche)"
},
{
"message": "11 mn",
"destination": "La Defense (Grande Arche)"
},
{
"message": "15 mn",
"destination": "La Defense (Grande Arche)"
}
]
},
"_metadata": {
"call": "GET /schedules/metros/1/berault/A",
"date": "2021-12-19T12:36:19+01:00",
"version": 4
}}
Im trying to get the content of the "message" keys into 4 different variables and print them as strings like this :
message = 2 min
message2 = 6 min
message3 = 11 min
message4 = 15 min
Here is my code :
#include <json-c/json.h>
#include <stdio.h>
int main(int argc, char **argv) {
FILE *fp;
char buffer[1024];
struct json_object *parsed_json;
struct json_object *message;
struct json_object *message2;
struct json_object *message3;
struct json_object *message4;
fp = fopen("test.json","r");
fread(buffer, 2048, 1, fp);
fclose(fp);
parsed_json = json_tokener_parse(buffer);
json_object_object_get_ex(parsed_json, "message", &message);
json_object_object_get_ex(parsed_json, "message", &message2);
json_object_object_get_ex(parsed_json, "message", &message3);
json_object_object_get_ex(parsed_json, "message", &message4);
printf("Message: %s\n", json_object_get_string(message));
printf("Message: %s\n", json_object_get_string(message2));
printf("Message: %s\n", json_object_get_string(message3));
printf("Message: %s\n", json_object_get_string(message4));
}
but since my json have not the same structure as the one in the tutorial it doesn't work and return me this :
Message: (null)
Message: (null)
Message: (null)
Message: (null)
Process finished with exit code 0
Any advices highly appreciated !
The first issue is that you try to read 1 element with the size
2048into a buffer with the size1024. You should read elements of size1and not read more bytes than you have space for in the buffer.The next issue is that you try to parse what you've read without null terminating what you've read.
freaddoes not assume that you're working with strings and will not do that automatically.The third issue is that you are not looking up the message array before trying to access the individual elements.
I don't know much about this library so I will leave this with memory leaks. You'll have to read the documentation to fix that. It will do the lookup properly though: