diff --git a/src/include/json.h b/src/include/json.h new file mode 100644 index 0000000..a63d84b --- /dev/null +++ b/src/include/json.h @@ -0,0 +1,10 @@ +#include +#include "curl.h" + +#ifndef JSON_H +#define JSON_H + +void json_out(cJSON** json); +void get_json_book(get_response* resp, cJSON** query); + +#endif diff --git a/src/json.c b/src/json.c new file mode 100644 index 0000000..33e941a --- /dev/null +++ b/src/json.c @@ -0,0 +1,42 @@ +#include +#include +#include + +#include "include/curl.h" +#include "include/json.h" + +static bool check_valid_query(cJSON* query) {return (query->valueint != 0);} + +#define FILE_OUT "book.json" +void json_out(cJSON** json) +{ + FILE* f = fopen(FILE_OUT, "w"); + fprintf(f, "%s", cJSON_Print(*json)); + fclose(f); +} +#undef FILE_OUT + +void get_json_book(get_response* resp, cJSON** query) +{ + bool err; + cJSON* json; + + json = cJSON_Parse(resp->buf); + if (!json) { + const char* err_ptr = cJSON_GetErrorPtr(); + if (err_ptr) + fprintf(stderr, "cJSON_Parse: %s\n", err_ptr); + cJSON_Delete(json); + exit(EXIT_FAILURE); + } + + err = check_valid_query(cJSON_GetObjectItemCaseSensitive(json, "numFound")); + if (!err) { + fprintf(stderr, "ISBN not found!\n"); + exit(EXIT_SUCCESS); + } + + // first entry of the "docs" json entry, which is the search result + (*query) = cJSON_GetObjectItemCaseSensitive(json, "docs")->child; +} +