C語(yǔ)言作為一種常用的編程語(yǔ)言,可以輕松地獲取遠(yuǎn)程的JSON數(shù)據(jù)。JSON數(shù)據(jù)的獲取可以幫助我們實(shí)現(xiàn)各種功能,如數(shù)據(jù)可視化、數(shù)據(jù)存儲(chǔ)等。下面我們就來(lái)了解一下如何使用C語(yǔ)言獲取遠(yuǎn)程的JSON數(shù)據(jù)。
#include <stdio.h> #include <stdlib.h> #include <curl/curl.h> struct data { size_t size; char* content; }; static size_t callback(void* ptr, size_t size, size_t nmemb, struct data* stream) { size_t data_size = size * nmemb; stream->content = (char*)realloc(stream->content, stream->size + data_size + 1); if (stream->content == NULL) { printf("Failed to allocate memory for JSON data!\n"); return 0; } memcpy(&(stream->content[stream->size]), ptr, data_size); stream->size += data_size; stream->content[stream->size] = '\0'; return data_size; } char* get_json_data() { CURL* curl; CURLcode res; struct data stream; stream.content = (char*)malloc(1); stream.size = 0; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "YOUR_JSON_API_URL"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream); res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("Error: %s", curl_easy_strerror(res)); return NULL; } curl_easy_cleanup(curl); } curl_global_cleanup(); return stream.content; } int main(void) { char* json_data = get_json_data(); printf("%s", json_data); free(json_data); return 0; }
上述代碼使用CURL庫(kù)來(lái)獲取JSON數(shù)據(jù)。在回調(diào)函數(shù)中,我們將獲取到的數(shù)據(jù)存儲(chǔ)到一個(gè)結(jié)構(gòu)體中,然后返回給主函數(shù)。接著我們?cè)谥骱瘮?shù)中輸出獲取到的數(shù)據(jù)。