Здравствуйте.
Есть JSON выхлоп с yahoo weather такого вида:
{
"query": {
"count": 1,
"created": "2016-06-27T13:12:50Z",
"lang": "en-US",
"results": {
"channel": {
"units": {
...
},
...
"location": {
"city": "City",
"country": "Country",
"region": "Region"
},
"wind": {
...
},
...
"item": {
...
"condition": {
"code": "28",
"date": "Mon, 27 Jun 2016 03:00 PM EEST",
"temp": "30",
"text": "Mostly Cloudy"
},
...
Мне нужны значения query->results->channel->location->city query->results->channel->item->condition->{temp, text}. Как это сделать более красиво, используя json-c библиотеку, нежели в этом говнокоде:
static void get_json_items(struct json_object *jobj, const char *key)
{
struct json_object *tmp;
struct json_object *location;
struct json_object *condition;
struct json_object *temp;
struct json_object *text;
int exists;
/* enum json_type type; */
exists = json_object_object_get_ex(jobj, key, &tmp);
if (!exists) {
printf("%s is not found in JSON\n", key);
return;
}
exists = json_object_object_get_ex(tmp, "results", &tmp);
if (!exists) {
printf("\"results\" is not found\n");
return;
}
exists = json_object_object_get_ex(tmp, "channel", &tmp);
if (!exists) {
printf("\"channel\" is not found\n");
return;
}
exists = json_object_object_get_ex(tmp, "location", &location);
if (!exists) {
printf("\"location\" is not found\n");
return;
}
exists = json_object_object_get_ex(location, "city", &location);
if (!exists) {
printf("\"city\" is not found\n");
return;
}
exists = json_object_object_get_ex(tmp, "item", &tmp);
if (!exists) {
printf("\"item\" is not found\n");
return;
}
exists = json_object_object_get_ex(tmp, "condition", &condition);
if (!exists) {
printf("\"condition\" is not found\n");
return;
}
exists = json_object_object_get_ex(condition, "temp", &temp);
if (!exists) {
printf("\"temp\" is not found\n");
return;
}
exists = json_object_object_get_ex(condition, "text", &text);
if (!exists) {
printf("\"text\" is not found\n");
return;
}
printf("DBG >>>\n");
/* printf("---\nlocation: %s\n---\n", json_object_to_json_string(location)); */
/* printf("---\nitem: %s\n---\n", json_object_to_json_string(tmp)); */
printf("city: %s\n",
json_object_get_string(location)
);
printf("temp: %s\n",
json_object_get_string(temp)
);
printf("text: %s\n",
json_object_get_string(text)
);
printf("DBG <<<\n");
}
Вот сам выхлоп бинарника:
gcc -Wall -Wextra -Wpedantic -std=c99 -I/usr/include/json-c/ -g3 -lcurl -ljson-c foo.c -o foo && ./foo
foo.c: In function 'main':
foo.c:218:25: warning: unused variable 'tmp' [-Wunused-variable]
struct json_object *tmp;
^~~
DBG >>>
city: City
temp: 23
text: Cloudy