简体   繁体   English

C ++的JSON解析器

[英]JSON parser for C++

I'm trying to parse Json file and store the data into 2D array or vector. 我正在尝试解析Json文件并将数据存储到2D数组或向量中。 The Json file looks like this: Json文件如下所示:

{"n" : 2,
 "x" : [[1,2],
        [0,4]]}

And this is what my code looks like and but I keep getting "json.exception.parse_error.101" error 这就是我的代码的样子,但是我不断收到“ 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;
}

In short, you need to take checking before processing, like below: 简而言之,您需要在处理之前进行检查,如下所示:

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
    }
}

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 : 关于如何临时消除该问题以便可以测试其余代码的一个明显示例,您可以考虑从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. 您将编译器<json-install-directory>/include为要搜索的目录,并且您的代码使用#include <nlohmann/json.hpp>包括标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM