C語言是一種強大的編程語言,可以用于許多不同的領域,包括獲取網頁上的JSON。獲取JSON有兩種方法:使用現有的庫或通過手動解析。
//方法一:使用現有的庫 #include#include #include #include int main() { CURL *curl; CURLcode res; char *url = "https://jsonplaceholder.typicode.com/todos/1"; char *json_string; json_t *root; json_error_t error; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); res = curl_easy_perform(curl); if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); curl_global_cleanup(); return 1; } json_string = curl_easy_strerror(curl, CURLOPT_WRITEFUNCTION, json_string); root = json_loads(json_string, 0, &error); printf("JSON Object:\n%s\n", json_dumps(root, JSON_ENCODE_ANY)); json_decref(root); curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; } //方法二:手動解析JSON #include #include #include typedef struct { char *data; size_t size; } MemoryStruct; void *httpget(const char *url) { CURL *curl; CURLcode res; MemoryStruct *chunk = malloc(sizeof(MemoryStruct)); chunk->size = 0; chunk->data = malloc(1); curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, chunk); res = curl_easy_perform(curl); if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); free(chunk->data); free(chunk); curl_easy_cleanup(curl); curl_global_cleanup(); return NULL; } curl_easy_cleanup(curl); } curl_global_cleanup(); return chunk; } int main() { char *url = "https://jsonplaceholder.typicode.com/todos/1"; char *httpget_output; MemoryStruct *chunk; int len; char *buffer; httpget_output = httpget(url); if(!httpget_output) { printf("Failed to perform HTTP GET request!\n"); return 1; } chunk = (MemoryStruct *)httpget_output; len = chunk->size; buffer = (char *)malloc(len); if(!buffer) { printf("Failed to allocate memory!\n"); free(chunk->data); free(chunk); return 1; } memcpy(buffer, chunk->data, len); // 解析 JSON 數據并提取所需信息 free(chunk->data); free(chunk); free(buffer); return 0; }
無論您選擇哪種方法,都需要使用CURL庫來獲取JSON數據。安裝CURL庫后,您可以輕松獲取網頁上的JSON數據。如果JSON數據較大,則手動解析可能需要更多時間和努力,但是使用現有的庫則可以使整個過程變得更加便捷。