我有一个字符串,我想解析成json,但_json
似乎每次都不起作用。
#include <nlohmann/json.hpp>
#include <iostream>
using nlohmann::json;
int main()
{
// Works as expected
json first = "[\"nlohmann\", \"json\"]"_json;
// Doesn't work
std::string s = "[\"nlohmann\", \"json\"]"_json;
json second = s;
}
第一部分有效,第二部分有效terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.302] type must be string, but is array
。
答案 0 :(得分:0)
将_json
添加到字符串文字中会指示编译器将其解释为JSON文字。
显然,JSON对象可以等于JSON值,但字符串不能。
在这种情况下,您必须从文字中删除_json
,但这会使second
隐藏在JSON对象中的字符串值。
所以,您也使用json::parse
,如下所示:
std::string s = "[\"nlohmann\", \"json\"]";
json second = json::parse(s);