c++ - C++ 的 JSON 解析器

标签 c++ json nlohmann-json

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

关于c++ - C++ 的 JSON 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57964785/

相关文章:

c++ - 创建和修改系统路径变量

java - 如何在 Restful Web 服务上接收 Json 对象?

c++ - 在for循环的某些迭代中,字符串的长度为0,而在其他迭代中则不是

c++ - 在按下 Arduino 上的特定键盘按钮之前,如何让步进电机运行?

c++ - C++:在constexpr构造函数中初始化成员数组

json - Dart:从字符串中获取枚举?

c++ - 交叉编译错误 Visual Studio C++

c++ - 从 Visual Studio 中间窗口调用方法 nlohmann::json::dump

c++ - 为什么构造函数在某些情况下不起作用?

java - 递归对象到 JSON