adds some basic json parsing stuff

This commit is contained in:
Nathan Singer 2025-02-28 00:08:33 -05:00
parent a42421a083
commit d2a8f8d53d
2 changed files with 52 additions and 0 deletions

10
src/include/json.h Normal file
View File

@ -0,0 +1,10 @@
#include <cjson/cJSON.h>
#include "curl.h"
#ifndef JSON_H
#define JSON_H
void json_out(cJSON** json);
void get_json_book(get_response* resp, cJSON** query);
#endif

42
src/json.c Normal file
View File

@ -0,0 +1,42 @@
#include <cjson/cJSON.h>
#include <stdlib.h>
#include <stdbool.h>
#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;
}