How to read json file in C ++ line

My code is:

std::istringstream file("res/date.json"); std::ostringstream tmp; tmp<<file.rdbuf(); std::string s = tmp.str(); std::cout<<s<<std::endl; 

The output of res/date.json , while I really want it, is all the content of this json file.

+6
source share
3 answers

it

 std::istringstream file("res/date.json"); 

creates a stream (named file ) that is read from the string "res/date.json" .

it

 std::ifstream file("res/date.json"); 

creates a stream (named file ) that is read from a file called res/date.json .

See the difference?

+9
source

I found a good solution later. Using parser in fstream .

 std::ifstream ifile("res/test.json"); Json::Reader reader; Json::Value root; if (ifile != NULL && reader.parse(ifile, root)) { const Json::Value arrayDest = root["dest"]; for (unsigned int i = 0; i < arrayDest.size(); i++) { if (!arrayDest[i].isMember("name")) continue; std::string out; out = arrayDest[i]["name"].asString(); std::cout << out << "\n"; } } 
+3
source

I tried the things above, but the fact is that they do not work in C ++ 14 for me: P I get something like ifstream incomplete type is not allowed in both answers And 2 json11 :: Json does not have ::Reader or ::Value , so answer 2 does not work either I will thin out the answoer for ppl that use this https://github.com/dropbox/json11 - do something like this:

 ifstream ifile; int fsize; char * inBuf; ifile.open(file, ifstream::in); ifile.seekg(0, ios::end); fsize = (int)ifile.tellg(); ifile.seekg(0, ios::beg); inBuf = new char[fsize]; ifile.read(inBuf, fsize); string WINDOW_NAMES = string(inBuf); ifile.close(); delete[] inBuf; Json my_json = Json::object { { "detectlist", WINDOW_NAMES } }; while(looping == true) { for (auto s : Json::array(my_json)) { //code here. }; }; 

Note: this is in a loop as I wanted it to loop data. Please note: there are some errors in it, but at least I opened the file in contrast to the above.

0
source

All Articles