0

我正在尝试解析 Json 文件并将数据存储到二维数组或向量中。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;
}
4

2 回答 2

1

简而言之,您需要在处理之前进行检查,如下所示:

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
    }
}
于 2019-09-16T23:07:27.640 回答
0

I'd agree with the suggestion that what you're seeing probably stems from failing to open the file correctly. For one obvious example of how to temporarily eliminate that problem so you can test the rest of your code, you might consider reading the data in from an 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";
}

As an aside, also note how you're normally expected to include the header. You give the compiler <json-install-directory>/include as the directory to search, and your code uses #include <nlohmann/json.hpp> to include the header.

于 2019-09-16T23:25:59.493 回答