C語言是一種通用的高級編程語言,它可以被用于編寫操作系統、驅動程序、桌面應用程序和嵌入式系統等多種類型的應用程序。在這些應用程序中,需要使用數據庫來存儲和管理數據。在C語言中,我們可以使用JSON數據庫來進行存儲和管理數據。
#include#include #include #include #include #define URL "https://jsonplaceholder.typicode.com/users" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(ptr == NULL) { /* out of memory! */ printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } int main(void) { CURL *curl_handle; CURLcode res; struct MemoryStruct chunk; chunk.memory = malloc(1); // will be grown as needed by the realloc above chunk.size = 0; // no data at this point curl_global_init(CURL_GLOBAL_ALL); // init the curl session curl_handle = curl_easy_init(); // specify URL to get curl_easy_setopt(curl_handle, CURLOPT_URL, URL); // send all data to this function curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); // we pass our 'chunk' struct to the callback function curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); // some servers don't like requests that are made without a user-agent // field, so we provide one curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); // get it! res = curl_easy_perform(curl_handle); // check for errors if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("%lu bytes retrieved\n", (unsigned long)chunk.size); // parse json data json_object *jobj = json_tokener_parse(chunk.memory); printf("Parsed JSON: %s\n", json_object_to_json_string_ext(jobj, JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY)); } // cleanup curl stuff curl_easy_cleanup(curl_handle); free(chunk.memory); // we're done with libcurl, so clean it up curl_global_cleanup(); return 0; }
以上代碼使用Curl獲取JSON數據并將其解析為JSON對象。然后,我們打印了解析后的JSON對象。我們可以使用這種方式獲取和解析JSON數據,并存儲在數據庫中以供以后使用。