简体   繁体   中英

JSON parser for C++

I'm trying to parse Json file and store the data into 2D array or vector. The Json file looks like this:

{"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

#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 :

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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