Bob*_*bil 12 c++ string json nlohmann-json
我有一个字符串,我想将其解析为 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;
}
Run Code Online (Sandbox Code Playgroud)
第一部分有效,第二部分抛出terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.302] type must be string, but is array
。
Tom*_*oni 19
添加_json
到字符串文字会指示编译器将其解释为 JSON 文字。
显然,JSON 对象可以等于 JSON 值,但字符串不能。
在这些情况下,您必须_json
从文字中删除,但这会使second
字符串值隐藏在 JSON 对象内。
所以,你json::parse
这样调用:
std::string s = "[\"nlohmann\", \"json\"]";
json second = json::parse(s);
Run Code Online (Sandbox Code Playgroud)