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;  
}
相关推荐
lbh6 小时前
当我开始像写代码一样和AI对话,一切都变了
前端·openai·ai编程
巨斧空间掌门6 小时前
JDK17 下载 windows Linux
linux·运维·服务器
AI+程序员在路上7 小时前
CANopen 协议:介绍、调试命令与应用
linux·c语言·开发语言·网络
江畔何人初7 小时前
kube-apiserver、kube-proxy、Calico 关系
运维·服务器·网络·云原生·kubernetes
We་ct7 小时前
LeetCode 918. 环形子数组的最大和:两种解法详解
前端·数据结构·算法·leetcode·typescript·动态规划·取反
爱编码的小八嘎7 小时前
C语言完美演绎4-4
c语言
wefly20177 小时前
m3u8live.cn 在线M3U8播放器,免安装高效验流排错
前端·后端·python·音视频·前端开发工具
皮卡蛋炒饭.8 小时前
进程得控制
linux·运维·服务器
C澒8 小时前
微前端容器标准化 —— 公共能力篇:通用打印
前端·架构
德育处主任Pro8 小时前
前端元素转图片,dom-to-image-more入门教程
前端·javascript·vue.js