You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C语言中使用YAJL获取JSON对象的键

嘿,我来帮你搞定从YAJL提取JSON对象键的问题!其实思路和你处理数组的逻辑类似,核心都是靠回调函数,只不过针对对象要用到专门的yajl_map_key回调来捕获键。

我给你写个完整的示例代码,你可以直接参考:

#include <yajl/yajl_parse.h>
#include <stdio.h>
#include <string.h>

// 自定义上下文,用来传递我们要找的键和解析状态
typedef struct {
    char target_key[64]; // 比如我们要找的"Val"
    int found_key;       // 标记是否匹配到目标键
} parse_context;

// 捕获对象键的核心回调
static int handle_map_key(void *ctx, const unsigned char *key, size_t key_len) {
    parse_context *context = (parse_context *)ctx;
    
    // 把YAJL传过来的键转成C字符串(注意手动加结束符)
    char current_key[key_len + 1];
    strncpy(current_key, (const char *)key, key_len);
    current_key[key_len] = '\0';
    
    // 对比是否是我们要找的键
    if (strcmp(current_key, context->target_key) == 0) {
        printf("成功提取到目标键:%s\n", current_key);
        context->found_key = 1; // 标记已找到,方便后续捕获对应值(如果需要的话)
    }
    
    return 1; // 返回1表示继续解析,返回0会终止解析流程
}

// 可选:如果需要提取对应的值,加上这个字符串回调
static int handle_string(void *ctx, const unsigned char *val, size_t val_len) {
    parse_context *context = (parse_context *)ctx;
    
    if (context->found_key) {
        char value[val_len + 1];
        strncpy(value, (const char *)val, val_len);
        value[val_len] = '\0';
        printf("对应的值是:%s\n", value);
        context->found_key = 0; // 重置标记,避免重复处理
    }
    
    return 1;
}

int main() {
    // 你的目标JSON数据
    const char *json = "{ \"Val\":\"box\" }";
    size_t json_len = strlen(json);
    
    // 初始化上下文
    parse_context ctx;
    strcpy(ctx.target_key, "Val");
    ctx.found_key = 0;
    
    // 配置YAJL回调结构体,只保留我们需要的回调
    yajl_callbacks callbacks = {
        NULL, NULL, NULL, NULL, NULL,
        handle_string, // 处理字符串值的回调
        NULL, // 开始对象的回调(可选)
        handle_map_key, // 处理对象键的回调
        NULL, // 结束对象的回调(可选)
        NULL, NULL
    };
    
    // 创建YAJL解析器
    yajl_handle handle = yajl_alloc(&callbacks, NULL, &ctx);
    
    // 开始解析JSON
    yajl_status status = yajl_parse(handle, (const unsigned char *)json, json_len);
    
    // 完成解析收尾
    if (status == yajl_status_ok) {
        status = yajl_complete_parse(handle);
    }
    
    // 错误处理
    if (status != yajl_status_ok) {
        unsigned char *error_msg = yajl_get_error(handle, 1, (const unsigned char *)json, json_len);
        printf("JSON解析出错:%s\n", error_msg);
        yajl_free_error(handle, error_msg);
    }
    
    // 清理资源
    yajl_free(handle);
    
    return 0;
}

关键说明:

  • parse_context结构体是用来在回调函数和主函数之间传递数据的——比如我们要找的目标键,以及是否找到的状态,这样回调就知道要匹配什么。
  • handle_map_key是核心:每次YAJL遇到JSON对象的键时,都会调用这个函数,把键的内容和长度传进来。我们只需要把它转成C字符串,然后和目标键对比就行。
  • 如果还需要提取键对应的值,就加上handle_string回调,利用found_key标记来捕获对应的值。

编译的时候记得链接YAJL库:

gcc your_code.c -lyajl -o json_parser

运行后就能看到输出:

成功提取到目标键:Val
对应的值是:box

内容的提问来源于stack exchange,提问作者Hemant Zope

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:37:06