started print_results() function

This commit is contained in:
Emma Tebibyte 2023-06-15 16:13:05 -06:00
parent 299ac1f200
commit dc2e88b2d8
Signed by: emma
GPG Key ID: 6D661C738815E7DD

View File

@ -73,7 +73,11 @@ curl_read_data_t search(char *argv[], char *term) {
curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, error); curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, error);
res = curl_easy_perform(handle); res = curl_easy_perform(handle);
curl_easy_cleanup(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 { } else {
fprintf(stderr, "%s: failed to initialize curl.\n"); fprintf(stderr, "%s: failed to initialize curl.\n");
} }
@ -81,19 +85,39 @@ curl_read_data_t search(char *argv[], char *term) {
return json; return json;
} }
void parse_json(char *argv[], char* json) { json_t *parse_json(char *argv[], char* json) {
char *parsed_json; json_t *results;
json_error_t *error; json_error_t error;
char *pretty_print; json_t *json_val = json_loads(json, JSON_DECODE_ANY, &error);
json_t *json_val = json_loads(json, JSON_DECODE_ANY, error);
json_unpack(json_val, "{s:o}", parsed_json); if (!json_val) {
pretty_print = json_dumps(json_val, JSON_INDENT(2)); fprintf(stderr, "%s: Error parsing JSON: %s.", argv[0], error.text);
printf("%s\n", pretty_print); 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[]) { int main(int argc, char *argv[]) {
curl_read_data_t json; curl_read_data_t json;
json_t *results;
if (argc < 1) { if (argc < 1) {
fprintf(stderr, "Usage: %s terms...", argv[0]); fprintf(stderr, "Usage: %s terms...", argv[0]);
@ -102,7 +126,11 @@ int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) { for (int i = 1; i < argc; i++) {
json = search(argv, argv[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; }
} }