0

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;
}
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
5a9ar
  • 1
  • 2
  • 1
    Are you sure the file is opened successfully? Try adding `if (!i) return 1;`. – HolyBlackCat Sep 16 '19 at 21:50
  • [parse error 101](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_af1efc2468e6022be6e35fc2944cabe4d.html#af1efc2468e6022be6e35fc2944cabe4d) indicates a general syntax error. Catching the exception and printing out the detailed error message will be useful. – Shawn Sep 16 '19 at 22:39
  • Yeah, I think my file was not open. I fix it and now I'm able to read the data from the file, but how do I parse it and store the data into 2d vector. I want to store `int n = 2` and `vector< vector> x`. – 5a9ar Sep 23 '19 at 15:57

2 Answers2

1

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
    }
}
Boki
  • 637
  • 3
  • 12
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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111