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

标签 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 在抛出 '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);

How to create a JSON object from a string.

关于c++ - 你如何从 nlohmann json 中的字符串中获取 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50011977/

相关文章:

c++ - (c++) 使用 ifstream 将 .dat 文件读取为十六进制

c++ - Netbeans C++ 错误 : 193

c++ - 为 OpenGL 的顶点缓冲区对象动态打包数据

c++ - c++98 中的 move() 是什么?

javascript - 为什么 rollup.js 不在其输出中包含 - 排他性 - 导出的值?

jquery - 在Jquery中读取JSON字符串

android - 当 Button onClick 时使用 json 解析设置 TextView

在 C 中创建一个字符串堆栈

c# - 从完整路径中排除基目录(以及文件名)

c# - string.replace 不工作