I am trying to use the Jansson library to parse a JSON string. I am unable to parse it correctly. Here is my code in C++
std::string JSONString = "{\"Hostages\": [{\"Rescue\": \"help me!\",\"confidence\": 0.01}]}";
json_t *JsonTable, *Rescue, *Hostages;
json_error_t JsonError;
if (JSONString.c_str()) {
JsonTable = json_loads(JSONString.c_str(), 0, &JsonError);
if (!JsonTable) {
printf("JSON parsing error: on line %d: %s\n", JsonError.line,
JsonError.text);
}
if (!json_is_object(JsonTable)) {
printf("JSON Pased root is not an array : Invalid response received\n");
json_decref(JsonTable);
}
Hostages = json_object_get(JsonTable, "Hostages");
if (!json_is_array(Hostages)) {
printf("error: Hostages is not array\n");
json_decref(JsonTable);
return 1;
} else {
Hostages = json_array_get(Hostages, json_array_size(Hostages));
Rescue = json_object_get(Hostages,"Rescue");
if (!json_is_string(Rescue)) {
printf("error: Rescue is not string\n");
json_decref(JsonTable);
return 1;
} else {
}
}
}
I dont understand whether Rescue
is a string, object or an array. I tried all three options as if (!json_is_string(Rescue))
, if (!json_is_array(Rescue))
& if (!json_is_object(Rescue))
but it always prints "error: Rescue is not string".
Any help please ?
You are trying to access the incorrect element of the array.
Take for example an array A = [{},{},{}];
of 3 elements, the size of this array is 3
so you can access the places as 0
, 1
, 2
only.
in your post you are accessing A[sizeof(A)]
as Hostages = json_array_get(Hostages, json_array_size(Hostages));
You can run a loop over it to access all the elements of your array, in your case just one. so you may access it as Hostages = json_array_get(Hostages, 0);