requests
库来获取网页内容,然后使用 json
模块解析 JSON 数据。以下是一个简单的示例代码:,,“python,import requests,import json,,# 发送HTTP请求获取网页内容,url = 'http://example.com/data.json',response = requests.get(url),,# 确保请求成功,if response.status_code == 200:, # 解析JSON数据, data = json.loads(response.text), print(data),else:, print('Failed to retrieve data'),
`,,请将
‘http://example.com/data.json’` 替换为实际的 URL。在C语言中读取网页上的JSON数据库通常涉及以下几个步骤:发送HTTP请求、接收响应数据、解析JSON格式的数据,以下是详细的操作步骤和示例代码。
发送HTTP请求
需要使用C语言向目标URL发送HTTP请求,这可以通过libcurl
库来实现。libcurl
是一个开源的客户端URL传输库,支持多种协议,包括HTTP、HTTPS等。
安装libcurl
在Linux系统上,可以使用以下命令安装libcurl:
sudo apt-get install libcurl4-openssl-dev
编写代码发送HTTP请求
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> struct MemoryStruct { char *memory; size_t size; }; 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) { printf("not enough memory (realloc returned NULL) "); 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); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, "http://example.com/data.json"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); res = curl_easy_perform(curl_handle); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s ", curl_easy_strerror(res)); } else { printf("%lu bytes retrieved ", (unsigned long)chunk.size); printf("Data: %s ", chunk.memory); } curl_easy_cleanup(curl_handle); free(chunk.memory); curl_global_cleanup(); return 0; }
解析JSON数据
接收到的JSON数据需要解析成可用的结构体或变量,可以使用cJSON
库来解析JSON数据。cJSON
是一个轻量级的JSON处理库。
安装cJSON
在Linux系统上,可以使用以下命令安装cJSON:
sudo apt-get install libcjson-dev
编写代码解析JSON数据
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <cjson/cJSON.h> void parse_json(const char *json_string) { cJSON *json = cJSON_Parse(json_string); if (json == NULL) { const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { fprintf(stderr, "Error before: %s ", error_ptr); } return; } cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name"); cJSON *age = cJSON_GetObjectItemCaseSensitive(json, "age"); if (cJSON_IsString(name) && (name->valuestring != NULL)) { printf("Name: %s ", name->valuestring); } if (cJSON_IsNumber(age)) { printf("Age: %d ", age->valueint); } cJSON_Delete(json); } int main() { const char *json_string = "{"name": "John", "age": 30}"; parse_json(json_string); return 0; }
综合示例
将上述两个步骤结合起来,实现一个完整的程序,从网页读取JSON数据并解析。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include <cjson/cJSON.h> struct MemoryStruct { char *memory; size_t size; }; 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) { printf("not enough memory (realloc returned NULL) "); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void parse_json(const char *json_string) { cJSON *json = cJSON_Parse(json_string); if (json == NULL) { const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { fprintf(stderr, "Error before: %s ", error_ptr); } return; } cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name"); cJSON *age = cJSON_GetObjectItemCaseSenSensitive(json, "age"); if (cJSON_IsString(name) && (name->valuestring != NULL)) { printf("Name: %s ", name->valuestring); } if (cJSON_IsNumber(age)) { printf("Age: %d ", age->valueint); } cJSON_Delete(json); } 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); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, "http://example.com/data.json"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); res = curl_easy_perform(curl_handle); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s ", curl_easy_strerror(res)); } else { printf("%lu bytes retrieved ", (unsigned long)chunk.size); printf("Data: %s ", chunk.memory); parse_json(chunk.memory); } curl_easy_cleanup(curl_handle); free(chunk.memory); curl_global_cleanup(); return 0; }
常见问题FAQs
Q1: 如果网页返回的JSON数据结构复杂怎么办?
A: 可以使用递归函数来遍历和解析复杂的JSON结构。cJSON
库提供了丰富的API来处理嵌套的JSON对象和数组,可以使用cJSON_GetObjectItem
和cJSON_GetArrayItem
来访问嵌套的对象和数组。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1493707.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复