用于C++的 JSON 解析器
JSON parser for C++
我正在尝试解析Json文件并将数据存储到2D数组或矢量中。Json 文件如下所示:
{"n" : 2,
"x" : [[1,2],
[0,4]]}
这就是我的代码的样子,但我不断收到"json.exception.parse_error.101"错误
#include <iostream>
#include "json.hpp"
#include <fstream>
using json = nlohmann::json;
using namespace std;
int main(int argc, const char * argv[]) {
ifstream i("trivial.json");
json j;
i >> j;
return 0;
}
简而言之,您需要在处理前进行检查,如下所示:
ifstream i("trivial.json");
if (i.good()) {
json j;
try {
i >> j;
}
catch (const std::exception& e) {
//error, log or take some error handling
return 1;
}
if (!j.empty()) {
// make further processing
}
}
我同意这样的建议,即您所看到的可能源于无法正确打开文件。有关如何暂时消除该问题以便测试其余代码的一个明显示例,您可以考虑从istringstream
读取数据:
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
#include <sstream>
using json = nlohmann::json;
using namespace std;
int main(int argc, const char * argv[]) {
std::istringstream i(R"(
{"n" : 2,
"x" : [[1,2],
[0,4]]}
)");
json j;
i >> j;
// Format and display the data:
std::cout << std::setw(4) << j << "n";
}
顺便说一句,还要注意您通常应该如何包含标题。将编译器<json-install-directory>/include
作为要搜索的目录,代码使用#include <nlohmann/json.hpp>
来包含标头。
相关文章:
- 在c++中使用nlohmann从类到json的转换
- C++json插入数组
- nlohmann-json将一个数组插入到另一个数组中
- 如何使用curlpp通过POST方法上传文件和json数据
- JSON转换为nlohmann JSON-lib中的结构数组
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在 nlohmann 的 json 库中获取数组长度?
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray
- 如何在特定位置追加 json 文件
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- 使用 jsoncpp 解析 json 数组字符串
- 将 FlatBuffer 对象序列化为 JSON,而不使用其架构文件
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 使用 cmake 生成 compile_commands.json
- 如何使用 c++ 和提升库生成 json
- 使用 minijson-reader 库读取 JSON 字符串时出现问题
- 使用 Qt 解析 JSON 数组
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- 在 C++ 中访问 JSON 数组值