C++ string to Json nlohmann

127 Views Asked by At

I get a Json variable j_res, its content is "{\"requirement\":\"follow\",\"responseflag\":\"yes\"}", I want to get the responseflag and requirement info. I try to convert the message to Json format, and get the requirement and responseflag value。I tried several ways,but failed.

Way 1:

using Json = nlohmann::json;

std::string responseflag = j_res.at("responseflag").dump();

error info is terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_2::detail::out_of_range' what(): [json.exception.out_of_range.403] key 'responseflag' not found

Way2:

using Json = nlohmann::json;

Json j_res2 = Json::parse(j_res.c_str());
std::string requirement = j_res2.at("requirement");

error info is

error: conversion from ‘nlohmann::json_abi_v3_11_2::basic_json<>::value_type’ {aka ‘nlohmann::json_abi_v3_11_2::basic_json<>’} to non-scalar type ‘std::__cxx11::string’ {aka ‘std::__cxx11::basic_string<char>’} requested
std::string requirement = j_res2.at("requirement");

I have remove the leading and trailing double quotes, backslash, it doesn't work. How can i get the responseflag and requirement info, thanks!

1

There are 1 best solutions below

0
On

I have solved this problem

using Json = nlohmann::json;

rm_double_quote(j_res); // my function
rm_backslash(j_res); // my function
auto j_res2 = Json::parse(j_res.c_str());
std::string str_responseflag = j_res2.at("responseflag").dump();

the key is auto j_res2 = Json::parse(j_res.c_str()); the type must be auto, cannot be std::string