C语言循环访问cJSON的数据

#include <stdio.h>
#include <stdlib.com>
#include “cJSON.h”

void print_cJSON_item(cJSON *item) {
if (!item) return;

switch ((item->type) & 255) {
    case cJSON_True:
    case cJSON_False:
        printf("%s: %s\n", item->string, (item->type == cJSON_True) ? "true" : "false");
        break;
    case cJSON_Number:
        printf("%s: %lf\n", item->string, item->valuedouble);
        break;
    case cJSON_String:
        printf("%s: %s\n", item->string, item->valuestring);
        break;
    case cJSON_Array:
    case cJSON_Object:
        printf("%s:\n", item->string);
        break;
    case cJSON_Null:
        printf("%s: null\n", item->string);
        break;
    default:
        printf("Unhandled type: %d\n", item->type);
        break;
}

}

void traverse_cJSON(cJSON *root) {
// Base case
if (!root) return;

// Recurse on objects and arrays
if (cJSON_IsObject(root) || cJSON_IsArray(root)) {
    cJSON *child = root->child;
    while (child) {
        print_cJSON_item(child);
        traverse_cJSON(child);  // Recurse
        child = child->next;
    }
} else {
    print_cJSON_item(root);
}

}

int main() {
const char *json_data = “{“name”:“John”,“age”:30,“cars”:[“Ford”,“BMW”,“Fiat”]}”;
cJSON *root = cJSON_Parse(json_data);

if (root == NULL) {
    const char *error_ptr = cJSON_GetErrorPtr();
    if (error_ptr != NULL) {
        fprintf(stderr, "Error before: %s\n", error_ptr);
    }
    return 1;
}

traverse_cJSON(root);

cJSON_Delete(root);

return 0;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值