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

26,859

Solution 1

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?

Solution 2

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

Solution 3

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;
}
Share:
26,859
aiziyuer
Author by

aiziyuer

To the honor of the roads are not covered with flowers

Updated on December 05, 2020

Comments

  • aiziyuer
    aiziyuer over 3 years

    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.

  • STF
    STF over 8 years
    How can I have the Json::Reader in my c++ project?
  • Darkgaze
    Darkgaze over 3 years
    My json parser fails using this method, but If I write the json text directly to a string by hand, it works... what is this doing with the text format?