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

使用RapidJSON在C++中解析JSON对象数组并获取指定属性值

在C++中解析JSON并提取特定属性值

在C里处理JSON,最省心的方案之一是用nlohmann/json这个轻量级库——它是单头文件实现,不用编译链接,直接include就能用,对C11及以上版本都兼容。下面是针对你需求的完整实现:

步骤1:准备库

你可以下载json.hpp头文件放到项目目录,或者用vcpkg、conan这类包管理工具安装,上手非常快。

步骤2:实现解析逻辑

先补全你提供的JSON片段(假设完整结构如下):

{ 
  "active": true, 
  "apiTier": 0, 
  "attributes": [ 
    { 
      "description": "Given in the datasheet as '0.33 kg (0.73 lbm)'.", 
      "maximumValue": "", 
      "measurementUnit": "kg", 
      "minimumValue": "", 
      "name": "mass", 
      "value": "0.33"
    },
    {
      "name": "size",
      "value": "10cm"
    }
  ] 
}

对应的C++代码:

#include <nlohmann/json.hpp>
#include <iostream>
#include <string>
#include <fstream>

// 简化命名,避免重复写nlohmann::json
using json = nlohmann::json;

int main() {
    // 方式1:从字符串解析(适合快速测试)
    std::string json_str = R"(
    { 
      "active": true, 
      "apiTier": 0, 
      "attributes": [ 
        { 
          "description": "Given in the datasheet as '0.33 kg (0.73 lbm)'.", 
          "maximumValue": "", 
          "measurementUnit": "kg", 
          "minimumValue": "", 
          "name": "mass", 
          "value": "0.33"
        },
        {
          "name": "size",
          "value": "10cm"
        }
      ] 
    }
    )";

    // 方式2:从本地文件解析(实际项目更常用)
    // std::ifstream json_file("your_target_file.json");
    // if (!json_file.is_open()) {
    //     std::cerr << "无法打开JSON文件,请检查路径" << std::endl;
    //     return 1;
    // }

    try {
        // 选择一种解析方式:字符串或文件
        json data = json::parse(json_str);
        // json data;
        // json_file >> data;

        // 先确认attributes字段存在且是数组类型
        if (data.contains("attributes") && data["attributes"].is_array()) {
            // 遍历attributes数组里的每个属性对象
            for (const auto& attr : data["attributes"]) {
                // 确保当前对象同时有name和value字段,避免访问不存在的键
                if (attr.contains("name") && attr.contains("value")) {
                    std::string attr_name = attr["name"];
                    if (attr_name == "mass") {
                        std::string attr_value = attr["value"];
                        std::cout << "mass对应的value值:" << attr_value << std::endl;
                        // 如果只需要第一个匹配项,找到后直接跳出循环即可
                        break;
                    }
                }
            }
        } else {
            std::cerr << "JSON中未找到有效的attributes数组" << std::endl;
        }
    } catch (const json::parse_error& e) {
        std::cerr << "JSON解析失败:" << e.what() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "程序出错:" << e.what() << std::endl;
    }

    return 0;
}

代码说明

  • 异常处理:捕获解析错误和通用异常,避免程序崩溃,同时给出明确的错误提示。
  • 安全检查:用contains验证键是否存在,is_array确认类型,防止访问不存在的字段或错误类型导致的未定义行为。
  • 灵活性:支持从字符串或本地文件解析,你可以根据实际场景切换。

如果你的项目已经使用C++23,也可以直接用标准库的<json>头文件,API和nlohmann/json几乎一致,只需要把命名空间换成std::json即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:55:52