c,#include,#include,#include "cJSON.h",,int main() {, const char *json_string = "[{\"name\": \"John\", \"age\": 30}, {\"name\": \"Jane\", \"age\": 25}]";, cJSON *json_array = cJSON_Parse(json_string);, if (json_array == NULL) {, printf("Error parsing JSON\n");, return 1;, },, int array_size = cJSON_GetArraySize(json_array);, for (int i = 0; i< array_size; i++) {, cJSON *item = cJSON_GetArrayItem(json_array, i);, if (item == NULL) continue;,, cJSON *name = cJSON_GetObjectItem(item, "name");, cJSON *age = cJSON_GetObjectItem(item, "age");,, if (cJSON_IsString(name) && (name->valuestring != NULL)) {, printf("Name: %s\n", name->valuestring);, }, if (cJSON_IsNumber(age)) {, printf("Age: %d\n", age->valueint);, }, },, cJSON_Delete(json_array);, return 0;,},“,,这个代码片段展示了如何使用cJSON库解析一个包含多个对象的JSON数组,并打印每个对象中的“name”和“age”字段。在C语言中读取JSON数组涉及到解析JSON格式的数据,由于C语言标准库并不直接支持JSON,我们需要使用第三方库来进行解析,常用的JSON解析库有cJSON、Jansson和json-c等,本文将介绍如何使用cJSON库来读取JSON数组,并提供相关示例代码。

安装和引入cJSON库

你需要下载并安装cJSON库,你可以从[cJSON的GitHub页面](https://github.com/DaveGamble/cJSON)获取源码,然后按照说明进行编译和安装。
在你的C项目中,需要包含cJSON头文件:
#include <cjson/cJSON.h>
读取JSON数组的基本步骤
1、加载JSON数据:将JSON字符串加载到内存中。
2、解析JSON数据:使用cJSON库函数将JSON字符串解析为cJSON对象。
3、遍历JSON数组:通过cJSON提供的API遍历JSON数组中的每个元素。
4、处理JSON数据:根据需要提取和处理JSON数组中的值。
5、释放内存:在使用完cJSON对象后,释放分配的内存。
示例代码
以下是一个完整的示例代码,展示了如何读取和处理一个JSON数组:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cjson/cJSON.h>
// 函数声明
void parse_json_array(const char *json_str);
int main() {
// JSON数组字符串
const char *json_str = "[\"apple\", \"banana\", \"cherry\"]";
// 调用函数解析JSON数组
parse_json_array(json_str);
return 0;
}
// 解析JSON数组的函数
void parse_json_array(const char *json_str) {
// 将JSON字符串解析为cJSON对象
cJSON *json = cJSON_Parse(json_str);
if (json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s
", error_ptr);
}
return;
}
// 确保解析的对象是一个数组
if (!cJSON_IsArray(json)) {
fprintf(stderr, "The provided JSON is not an array.
");
cJSON_Delete(json);
return;
}
// 获取数组的长度
int array_size = cJSON_GetArraySize(json);
printf("Array size: %d
", array_size);
// 遍历数组中的每个元素
for (int i = 0; i < array_size; i++) {
// 获取数组中的第i个元素
cJSON *element = cJSON_GetArrayItem(json, i);
// 确保元素是字符串类型
if (cJSON_IsString(element)) {
// 获取字符串内容
const char *string_value = cJSON_GetStringValue(element);
printf("Element %d: %s
", i, string_value);
} else {
fprintf(stderr, "Element %d is not a string.
", i);
}
}
// 释放cJSON对象
cJSON_Delete(json);
}相关问题与解答
问题1:如何判断JSON对象是否为数组?

答:可以使用cJSON_IsArray函数来判断一个cJSON对象是否为数组。
if (!cJSON_IsArray(json)) {
fprintf(stderr, "The provided JSON is not an array.
");
cJSON_Delete(json);
return;
}问题2:如何获取JSON数组中的元素?
答:可以使用cJSON_GetArrayItem函数来获取数组中的指定元素。
for (int i = 0; i < array_size; i++) {
cJSON *element = cJSON_GetArrayItem(json, i);
// 处理元素...
}到此,以上就是小编对于“c读取json数组”的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/2999.html<
