用于C++的 JSON 解析器

JSON parser for C++

本文关键字:JSON C++ 用于      更新时间:2023-10-16

我正在尝试解析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>来包含标头。