我有一个字符串,我想将其解析为 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 在抛出 'nlohmann::detail::type_error' 实例后调用
what(): [json.exception.type_error.302] 类型必须是字符串,但是是数组
。
最佳答案
将 _json
添加到字符串文字指示编译器将其解释为 JSON 文字。
显然,JSON 对象可以等于 JSON 值,但字符串不能。
在这种情况下,您必须从文字中删除 _json
,但这会使 second
成为隐藏在 JSON 对象中的字符串值。
因此,您还可以使用 json::parse
,如下所示:
std::string s = "[\"nlohmann\", \"json\"]";
json second = json::parse(s);
关于c++ - 你如何从 nlohmann json 中的字符串中获取 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50011977/