繁体   English   中英

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>包括标头。

暂无
暂无

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

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