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

如何使用nlohmann/json将字符串转为列表并遍历该列表?

解决JSON中字符串包裹数组的解析与遍历问题

假设你的calibration.json结构类似这样:

{
  "lidar_calibration": "[{\"id\":0,\"offset_x\":0.1},{\"id\":1,\"offset_x\":0.2}]"
}

这里lidar_calibration的值是字符串形式的JSON数组,常规解析只会拿到字符串,无法直接遍历。用C++处理的核心思路是:先解析外层JSON拿到这个字符串,再把字符串二次解析为JSON数组,之后就能正常遍历。

下面用主流的nlohmann/json库(轻量头文件库,无需编译)实现完整流程:

步骤1:引入依赖

把nlohmann/json的头文件json.hpp放到项目目录,代码中引入:

#include <iostream>
#include <fstream>
#include "json.hpp"

using json = nlohmann::json;

步骤2:解析外层JSON并提取字符串

读取JSON文件,解析后取出lidar_calibration对应的字符串:

// 读取JSON文件
std::ifstream calib_file("calibration.json");
if (!calib_file.is_open()) {
    std::cerr << "无法打开calibration.json文件" << std::endl;
    return 1;
}

json root;
calib_file >> root;
calib_file.close();

// 提取字符串形式的数组
std::string calib_str = root["lidar_calibration"].get<std::string>();

步骤3:二次解析字符串为JSON数组

把提取到的字符串解析成JSON数组,之后就可以遍历:

try {
    json calib_array = json::parse(calib_str);
    
    // 遍历数组
    for (const auto& item : calib_array) {
        // 访问数组元素的字段,比如id和offset_x
        int id = item["id"].get<int>();
        float offset_x = item["offset_x"].get<float>();
        std::cout << "雷达ID: " << id << ", X偏移量: " << offset_x << std::endl;
    }
} catch (const json::parse_error& e) {
    std::cerr << "解析字符串数组失败: " << e.what() << std::endl;
    return 1;
}

关键说明

  • 如果使用其他JSON库(比如Qt的QJsonDocument),思路一致:先取字符串,再将字符串转为JSON数组。
  • 必须加异常捕获,避免字符串格式不合法导致程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:19:49