CJSON解析json字符串示例

cJSON 作为 Json 格式的解析库,其主要功能就是构建和解析 Json 格式

CJSON解析json字符串 {"action":"started","code":"0","data":"","desc":"success","sid":"a8"}

复制代码
#include <stdio.h>  
#include <stdlib.h>  
#include "cJSON.h"  
  
int main() {  
    char *json_string = "{\"action\":\"started\",\"code\":\"0\",\"data\":\"\",\"desc\":\"success\",\"sid\":\"a8\"}";  
      
    // 解析JSON字符串  
    cJSON *root = cJSON_Parse(json_string);  
    if (root == NULL) {  
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());  
        return 1;  
    }  
      
    // 获取各个字段的值  
    cJSON *action = cJSON_GetObjectItem(root, "action");  
    cJSON *code = cJSON_GetObjectItem(root, "code");  
    cJSON *data = cJSON_GetObjectItem(root, "data");  
    cJSON *desc = cJSON_GetObjectItem(root, "desc");  
    cJSON *sid = cJSON_GetObjectItem(root, "sid");  
      
    // 输出各个字段的值  
    printf("action: %s\n", action->valuestring);  
    printf("code: %s\n", code->valuestring);  
    printf("data: %s\n", data->valuestring);  
    printf("desc: %s\n", desc->valuestring);  
    printf("sid: %s\n", sid->valuestring);  
      
    // 释放内存  
    cJSON_Delete(root);  
      
    return 0;  
}
相关推荐
掘金安东尼31 分钟前
更多审查智能体,更少盲区:GitHub Copilot 代码审查是怎么做的
前端·github copilot
LabVIEW开发2 小时前
EXFO IQS-5100B + LabVIEW 光测试怎么做?
服务器·网络·labview
进击的荆棘3 小时前
Linux网络——应用层协议HTTP
linux·运维·服务器·网络·http
Hilaku3 小时前
2026 年了,jQuery 真的该死了吗?
前端·javascript·程序员
zach3 小时前
吃透 React setState 同步异步之谜:从批量更新、事件循环到版本演进的完整拆解
前端·react.js
不服老的小黑哥3 小时前
02-从 pnpm dev 到 Spring Boot 启动:后端服务到底怎么跑起来?
前端
htzyl2063 小时前
javaScript——this 的四种绑定:为什么箭头函数改不了它
前端·javascript
欧雷殿3 小时前
做自己的第一位客户:一人公司的数据治理公开实践
前端·ai编程·团队管理
虫无涯4 小时前
基于Frama-C形式化测评平台构想
嵌入式
掘金安东尼4 小时前
换上 Gemini 4 Neon 之后,我改了哪些上下文工程大模型
前端