c 通過url獲取json是一種常見的操作,它主要是通過訪問指定的url,獲取網頁上的json數據,以便進行相應的數據處理。
#include <stdio.h> #include <stdlib.h> #include <curl/curl.h> #include <jansson.h> static size_t callback(void *ptr, size_t size, size_t nmemb, void *stream) { size_t written = fwrite(ptr, size, nmemb, (FILE *)stream); return written; } int main(int argc, char *argv[]) { CURL *curl; FILE *fp; CURLcode res; char *url = "http://localhost:8080/books"; char outfilename[FILENAME_MAX] = "/tmp/books.json"; char *json_string; json_error_t error; json_t *json_data, *json_element; curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); } fp = fopen(outfilename, "r"); fseek(fp, 0, SEEK_END); long fsize = ftell(fp); fseek(fp, 0, SEEK_SET); json_string = malloc(fsize + 1); fread(json_string, fsize, 1, fp); fclose(fp); json_data = json_loads(json_string, 0, &error); if(!json_data) { fprintf(stderr, "error: on line %d: %s\n", error.line, error.text); exit(1); } size_t index; json_array_foreach(json_data, index, json_element) { json_t *id, *name; if(!json_object_get(json_element, "id") || !json_object_get(json_element, "name")) { continue; } id = json_object_get(json_element, "id"); name = json_object_get(json_element, "name"); if(!json_is_number(id) || !json_is_string(name)) { continue; } printf("id: %ld, name: %s\n", json_integer_value(id), json_string_value(name)); } json_decref(json_data); free(json_string); return 0; }
以上是一個通過url獲取json數據并進行處理的簡單示例代碼,主要利用了curl庫和jansson庫進行數據獲取和解析。其中,通過curl_easy_setopt設置相應的選項,如URL、回調函數等,實現從指定URL獲取數據。然后,利用jansson庫中的json_loads函數對獲取到的json字符串進行解析,并進行相應的數據處理。