i have the following JSON data in a .json
file:
[
{
"Type":"SET",
"routine":[
{
"ID":"1",
"InternalType":"Motorcycle",
"payload":"2"
},
{
"ID":"12",
"InternalType":"Chair"
}
]
},
{
"Type":"GET",
"routine":[
{
"ID":"1",
"InternalType":"Wheel"
},
{
"ID":"4",
"InternalType":"Car",
"payload":"6"
}
]
}
]
I try to check and parse the data as follows:
#include<iostream>
#include<fstream>
#include"json.hpp"
using json = nlohmann::json;;
using namespace std;
int main (){
string pathToFile = "/absolute/path/to/my/exampledata.json";
ifstream streamOfFile(pathToFile);
if(!json::accept(streamOfFile)){
cout << "JSON NOT VALID!" << endl;
} else {
cout << "Nothing to complain about!" << endl;
}
try {
json allRoutines = json::parse(streamOfFile);
} catch (json::parse_error& error){
cerr << "Parse error at byte: " << error.byte << endl;
}
return 0;
}
I compile an d run it as follows:
g myCode.cpp -o out
./out
Nothing to complain about!
Parse error at byte: 1
As I understood the function json::accept()
it should return true
if the JSON
data is valid.
https://json.nlohmann.me/api/basic_json/accept/
In my case you can see, that the accept()
function returns true on the data stream but throws a json::parse_error
on the actual parsing.
So I would like to know if anyone happens to see an error in my use of the two functions, the data or can explain to me why it behaves like that.
Kind Regards
CodePudding user response:
json::accept(streamOfFile)
reads from the input stream till the end.
json::parse(streamOfFile)
can't read after the input stream end.
This has nothing to do with the JSON library, it's a general feature of streams, once have been read, they come to the end of file state.
You might want to reset the stream to the zero file position, then parse the file
streamOfFile.clear(); // Reset eof state
streamOfFile.seekg(0, ios::beg) // Seek to the begin of the file
json allRoutines = json::parse(streamOfFile);