你如何从nlohmann json中的字符串中获取JSON对象?

时间:2018-04-24 23:22:02

标签: c++ json string 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;
}

第一部分有效,第二部分有效terminate called after throwing an instance of 'nlohmann::detail::type_error' what(): [json.exception.type_error.302] type must be string, but is array

1 个答案:

答案 0 :(得分:0)

_json添加到字符串文字中会指示编译器将其解释为JSON文字。

显然,JSON对象可以等于JSON值,但字符串不能。

在这种情况下,您必须从文字中删除_json,但这会使second隐藏在JSON对象中的字符串值。

所以,您也使用json::parse,如下所示:

std::string s = "[\"nlohmann\", \"json\"]";
json second = json::parse(s);

How to create a JSON object from a string.