Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 278
aiziyuer Avatar asked Dec 18 '12 14:12

aiziyuer


People also ask

Can C use JSON?

Parsing JSON in C using microjson Developed originally for server-browser communication, the use of JSON has since expanded into a universal data interchange format. This tutorial will provide a simple introduction to parsing JSON strings in the C programming language using the microjson library.

How do I read a JSON file as a string?

We use the readAllBytes() method of the Files class to read bytes data of the JSON files as a string. We store the returned result of the readAllBytes()and get()methods into a variable and return it to the main() method. In the main() method, we simply print the returned result of the convertFileIntoString()


1 Answers

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;
}
like image 193
PlsWork Avatar answered Oct 06 '22 17:10

PlsWork