aiziyuer
aiziyuer

Reputation: 160

How to read a json file into a C++ string

My code like this:

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

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

Upvotes: 11

Views: 35777

Answers (4)

PlsWork
PlsWork

Reputation: 2158

Load a .json file into an std::string and write it to the console:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

int main(int, char**) {

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

    return 0;
}

Upvotes: 3

PSXGamerPro1
PSXGamerPro1

Reputation: 182

I tried the stuff above but the thing is they dont work in C++ 14 for me :P I get stuff like from ifstream incomplete type is not allowedon both answers AND 2 json11::Json does not have a ::Reader or a ::Value so Answer 2 does not work either I thin the answoer for ppl who use this https://github.com/dropbox/json11 is to 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: that is is in a loop as I wanted it to loop the data. Note: there are bound to be some errors with this but at least I opened the file correctly unlike above.

Upvotes: 0

aiziyuer
aiziyuer

Reputation: 160

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";
    }
}

Upvotes: 4

Bart van Ingen Schenau
Bart van Ingen Schenau

Reputation: 15758

This

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

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

This

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

creates a stream (named file) that reads from the file named res/date.json.

See the difference?

Upvotes: 16

Related Questions