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

如何使用nlohmann::json解析JSON字符串获取指定字段值?

问题分析与解决方案

错误原因拆解

  1. 方法1报错原因:你直接对std::string类型的j_res调用nlohmann::json的at()方法——j_res是JSON格式的字符串,不是已经解析好的nlohmann::json对象,自然找不到对应的键。
  2. 方法2报错原因:j_res2.at("requirement")返回的是nlohmann::json类型的实例,不能直接赋值给std::string,必须显式转换为字符串类型。

可行解决方案

步骤1:确保JSON字符串格式正确

如果你的j_res原始内容带有首尾双引号(比如"{"requirement":"follow","responseflag":"yes"}"),先去除首尾的引号:

if (!j_res.empty() && j_res.front() == '"' && j_res.back() == '"') {
    j_res = j_res.substr(1, j_res.size() - 2);
}

步骤2:解析字符串并提取字段

使用nlohmann::json::parse()将字符串解析为JSON对象,再通过get<std::string>()显式转换值类型:

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

using Json = nlohmann::json;

int main() {
    std::string j_res = "{\"requirement\":\"follow\",\"responseflag\":\"yes\"}";
    
    // 处理可能的首尾双引号(如果有)
    if (!j_res.empty() && j_res.front() == '"' && j_res.back() == '"') {
        j_res = j_res.substr(1, j_res.size() - 2);
    }

    // 解析为JSON对象
    Json j_obj = Json::parse(j_res);

    // 安全提取字段(at()会在键不存在时抛出异常)
    std::string requirement = j_obj.at("requirement").get<std::string>();
    std::string responseflag = j_obj.at("responseflag").get<std::string>();

    // 或者使用operator[](键不存在时会插入默认值,适合不严格检查的场景)
    // std::string requirement = j_obj["requirement"].get<std::string>();
    // std::string responseflag = j_obj["responseflag"].get<std::string>();

    return 0;
}

补充说明

  • 如果你不需要严格检查键是否存在,operator[]比at()更简洁,但要注意它会在键不存在时自动插入一个默认值到JSON对象中。
  • 若字段值本身是字符串类型,get<std::string>()是最直接的转换方式;如果用dump(),会给字符串额外添加一层双引号,不推荐用于提取字段值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:25:28