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

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?


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

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