0

Currently I have a JSON file (Test.json) with some valid data in json format and i'am trying to parse the data using a json object (readData) using JsonCpp, as below

Json::Value readData;   
std::ifstream readFile("Test.json");  
readFile >> readData; 

This works fine if the json file is having valid contents in json format, but it crashes at "readFile >> readData" if the contents are not of a json format. is there any way to validate the file before assigning it to a json object in C++ ?

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Suchin Raj
  • 17
  • 2
  • 8
  • 1
    `std::ifstream readFile(Test.json);` won't compile. I believe you meant `std::ifstream readFile("Test.json");`. – Azeem Apr 23 '20 at 12:41
  • 3
    If it crashes, my best bet is that unsuccessful reads raise an exception. Try to reach for the documentation for confirmation or wrap your `>> `in a `try`-`catch` block and try to catch the correct excetpion. – Fureeish Apr 23 '20 at 12:41
  • 1
    Are you using [JsonCpp](https://github.com/open-source-parsers/jsoncpp) library? – Azeem Apr 23 '20 at 12:46
  • 3
    @Fureeish Indeed, http://open-source-parsers.github.io/jsoncpp-docs/doxygen/namespace_json.html#a4d245ef719cc0853e8e78eb5f99c16e5 says "std::exception on parse error". – Peter - Reinstate Monica Apr 23 '20 at 12:46
  • @Azeem yes i'am using jsoncpp library – Suchin Raj Apr 23 '20 at 12:49

2 Answers2

1

It doesn't "crash"; it throws an exception. I'd guess you're not catching that exception.

Anyway, for reading JSON you probably want to use parseFromStream. This allows you to set options, and returns true or false. The operator>> you're using is just a shortcut.

Please read documentation for the functions that you use. It's there to help you.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
0

I think you should use this code instead. It will not crash the program. It will just show you (on STDERR) what error has occurred.

Json::Value readData;   
std::ifstream readFile("Test.json");
if (readFile) {
    try {
        readFile >> readData; 
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
}
else {
    std::cerr << "File not found!" << std::endl;
}

According to the documentation of JsonCpp, operator>>() results in std::exception on parse error.

brc-dd
  • 10,788
  • 3
  • 47
  • 67