Json: Help for a Beginner?

Created on 26 May 2020  路  2Comments  路  Source: nlohmann/json

Hello,

I am trying to make a text based game and had the idea to use a json file to store all of the text for each page. And then I can conveniently turn the text into a json object and in my main.cpp output the text from the json file.

Because I am new (barely figured out how to get this library installed) I am having a hell of a time understanding the documentation. Is my stated objective possible?

The only thing I have figured out how to do is store text in a json file:

{
"text": "goes here"

}

and then in my main.cpp file I call that text by opening and reading into the file:

 std::ifstream inFile("pagetest.json");  
json j; 
inFile >> j; 
std::string s = j.dump(); 
std::cout << s << std::endl;

However, this does not behave as I'd expect. It outputs everything including the quotations and the {} which is what I don't want. I would need just a string outputted.

Basically I am very confused.... Any help would be greatly appreciated.

question proposed fix

All 2 comments

If you only need the value at key "text", do this:

std::cout << j["text"] << std::endl;

If you do not want the quotes (i.e., a serialize JSON value of type string), but a std::string, do this:

std::string s = j["text"];
std::cout << s << std::endl;

Fantastic that worked!!! So simple! Thank you for answering. I am slowly understanding the power of json.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jmlemetayer picture jmlemetayer  路  3Comments

MariaRamos89 picture MariaRamos89  路  4Comments

zkelo picture zkelo  路  3Comments

past-due picture past-due  路  4Comments

sqwunkly picture sqwunkly  路  3Comments