Skip to content

Getting std::invalid_argument: stream error when following example #429

Closed

Description

@aharbis

I'm new to the library, but following the example on the base README:

// read a JSON file
std::ifstream i("file.json");
json j;
i >> j;

I'm getting the following error:

libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stream error
Abort trap: 6

My code is as follows:

#include "json.hpp"
using json = nlohmann::json;

json json_obj;

std::ifstream input_json("./test/json/TestItems.json");

if (input_json.is_open())
{
    while (getline(input_json, line))
    {
        std::cout << line << std::endl;
    }
    input_json >> json_obj; // this line seems to cause the exception
    input_json.close();
}
else std::cout << "Unable to load file." << std::endl;

I've verified that input_file is ok, since I can iterate through the lines and print them out in the while loop. As soon as I add input_json >> json_obj I get the above exception.

Am I doing something wrong? Haven't been able to find any doc that says this shouldn't work.

Activity

  1. aharbis commented on Jan 15, 2017

    @aharbis
    Author

    To clarify, I'm using version 2.0.10 of json.hpp and building with C++11.

  2. aharbis commented on Jan 15, 2017

    @aharbis
    Author

    Additionally, this is the contents of TestItems.json:

    {
        "Items": {
            "Food": {
                "Apple": {
                    "Heal": 10,
                    "MaxStack": 20
                },
                "Bread": {
                    "Heal": 20,
                    "MaxStack": 20
                }
            }
        }
    }
  3. theodelrieu commented on Jan 15, 2017

    @theodelrieu
    Contributor

    The input_json stream reaches EOF after the getline loop, and is in an invalid state, hence the throw.

    To fix this, you can add those two lines right after the getline:

    input_json.clear(); // clear error/eof flags
    input_json.seekg(0); // go back to the beginning of the file
    input_json >> json_obj;

    However there is a better way to parse a stream with this library:

    std::ifstream ifs{"test.json"};
    
    auto parsed_json = json::parse(ifs);
    std::cout << parsed_json.dump() << std::endl;
  4. aharbis commented on Jan 15, 2017

    @aharbis
    Author

    Ah, of course. Thanks for the tip. I went with the json::parse() method since it appears to be a cleaner approach.

  5. nlohmann commented on Jan 16, 2017

    @nlohmann
    Owner

    I hope the error messages become clearer when #244 is merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions