C語言可以通過網絡庫libcurl來實現http讀取json數據。在使用之前需要先安裝libcurl庫,以Ubuntu為例:
sudo apt-get install libcurl4-openssl-dev
接下來就可以開始編寫代碼了:
#include <stdio.h>
#include <curl/curl.h>
#include <jansson.h>
#define URL "http://example.com/api/data"
int main(void) {
CURL *curl;
CURLcode res;
char *data;
json_t *root;
json_error_t error;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res == CURLE_OK) {
root = json_loads(data, 0, &error);
if(!root) {
fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
return 1;
}
// do something with json data
json_decref(root);
} else {
fprintf(stderr, "error: failed to fetch data: %s\n", curl_easy_strerror(res));
return 1;
}
free(data);
}
return 0;
}
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) {
size_t total_size = size * nmemb;
char **pstr = (char **)userdata;
*pstr = realloc(*pstr, total_size + 1);
if(*pstr) {
memcpy(&(*pstr)[strlen(*pstr)], ptr, total_size);
(*pstr)[total_size] = '\0';
}
return total_size;
}
代碼中用到的json_t和json_error_t數據結構是由開源JSON庫jansson提供的。在讀取到數據后需要調用json_loads函數來解析JSON字符串,解析完成后就可以像操作普通C數據一樣來操作JSON數據了。