[英]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>
包括標頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.