started print_results() function
This commit is contained in:
parent
299ac1f200
commit
dc2e88b2d8
50
searpent.c
50
searpent.c
@ -73,7 +73,11 @@ curl_read_data_t search(char *argv[], char *term) {
|
||||
curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, error);
|
||||
res = curl_easy_perform(handle);
|
||||
curl_easy_cleanup(handle);
|
||||
fprintf(stderr, "%s: %s", argv[0], error);
|
||||
|
||||
if (error != NULL) {
|
||||
fprintf(stderr, "%s: %s", argv[0], error);
|
||||
exit(EX_DATAERR);
|
||||
}
|
||||
} else {
|
||||
fprintf(stderr, "%s: failed to initialize curl.\n");
|
||||
}
|
||||
@ -81,19 +85,39 @@ curl_read_data_t search(char *argv[], char *term) {
|
||||
return json;
|
||||
}
|
||||
|
||||
void parse_json(char *argv[], char* json) {
|
||||
char *parsed_json;
|
||||
json_error_t *error;
|
||||
char *pretty_print;
|
||||
json_t *json_val = json_loads(json, JSON_DECODE_ANY, error);
|
||||
json_t *parse_json(char *argv[], char* json) {
|
||||
json_t *results;
|
||||
json_error_t error;
|
||||
json_t *json_val = json_loads(json, JSON_DECODE_ANY, &error);
|
||||
|
||||
json_unpack(json_val, "{s:o}", parsed_json);
|
||||
pretty_print = json_dumps(json_val, JSON_INDENT(2));
|
||||
printf("%s\n", pretty_print);
|
||||
if (!json_val) {
|
||||
fprintf(stderr, "%s: Error parsing JSON: %s.", argv[0], error.text);
|
||||
exit(EX_DATAERR);
|
||||
}
|
||||
|
||||
results = json_object_get(json_val, "results");
|
||||
|
||||
if (results == NULL) {
|
||||
fprintf(stderr, "%s: No results.", argv[0]);
|
||||
exit(EX_DATAERR);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
int print_results(json_t *results) {
|
||||
size_t index;
|
||||
json_t *value;
|
||||
|
||||
json_array_foreach(results, index, value) {
|
||||
printf("%s: %s\n", index, value);
|
||||
}
|
||||
return EX_OK;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
curl_read_data_t json;
|
||||
json_t *results;
|
||||
|
||||
if (argc < 1) {
|
||||
fprintf(stderr, "Usage: %s terms...", argv[0]);
|
||||
@ -102,7 +126,11 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
json = search(argv, argv[i]);
|
||||
parse_json(argv, json.data);
|
||||
results = parse_json(argv, json.data);
|
||||
}
|
||||
return EX_OK;
|
||||
|
||||
if (print_results(results) > 0) {
|
||||
printf("%s: Error printing results.\n", argv[0]);
|
||||
exit(1);
|
||||
} else { return EX_OK; }
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user