gpt4 book ai didi

c++ - 如何读取 C++ 中的 JSON 内容?

转载 作者:行者123 更新时间:2023-11-28 01:33:27 27 4
gpt4 key购买 nike

我正在尝试读取一个包含有效 JSON 内容但不是字符串的文本文件。如果是字符串转储,下面的代码可以正常工作。例如 - 如果文件内容像这样 "{\"happy\": true,\"pi\": 3.141 }" 然后它会解析无误。现在我想找出一种最小化这些转换的方法?如何使用任何标准库将 JSON 内容转换为 C++ 中的字符串转储?我目前正在使用 nlohmann,但这似乎需要额外的编码。如果我可以用简单的代码破解它,请教我。

我的代码

#include <iostream>
#include <fstream>
#include <streambuf>
#include <nlohmann/json.hpp>

using namespace std;
using json = nlohmann::json;

int main()
{
std::fstream f_json("C://json.txt");

json jFile;
try {
jFile = json::parse(f_json);
}
catch (json::parse_error &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}

我们的客户端生成如下所示的 JSON 文件。

{
"happy": true,
"pi": 3.141
}

最佳答案

我的文件在C:/test.json下,所以没有权限打开。现在我把它放在适当的文件夹中。现在它工作正常。

关于c++ - 如何读取 C++ 中的 JSON 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50517919/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com