c++jsonnlohmann-json

nlohmann json: Why am I getting a parse error?


I'm really confused why I'm getting a parse error when I'm trying to parse a file in C++ using the nlohmann library.

My code is exactly the same as one I copied from their GitHub page:

using json = nlohmann::json;

int main() {
    ifstream ifs("test.json");

    if (nlohmann::json::accept(ifs))
        cout << "accepted" << endl;
    else
        cout << "not accepted" << endl;

    json j = json::parse(ifs);
}

And the JSON file is just this:

{ 
   "test": 5
}

For some reason, this throws an error when I get to the parse() function, despite the accept() function returning true, which means the JSON was accepted as valid.

Also, when I do something like this:

json j = json::parse(R"({"test": "aaa"})");

That works fine. But I can't parse the ifstream object.

Does anyone have any idea what could possibly be the issue here?

I have no ideas, and I'm clueless, because it seems I did everything right.


Solution

  • Once nlohmann::json::accept has returned, the stream ifs has been consumed.

    When you later json::parse(ifs), you try to parse what is essentially an empty file, and an empty string is not a valid json document.

    You need to rewind the stream or reopen your file.

    // rewind
    // ifs.clear() isn't needed in C++11, as seekg() already clears the oefbit
    ifs.seekg(0);
    json j = json::parse(ifs);
    
    // reopen
    json j = json::parse(std::ifstream{"test.json"});