anderer455
anderer455

Reputation: 25

What is the easiest way to parse a json file using rapidjson?

So I am just getting familiar with rapidjson.h but I can't find this one basic piece of example code of parsing the *.json file.

I found the official [turorial][1]. But here however they parse the json stored in a C string. I know how this string is supposed to look like but I'm lazy to make a custom Parser just to convert my file to this string. I mean I was kinda hoping that rapidjson is supposed to do that for me. Please correct me if I'm wrong.

The closest thing I found to what I need is here How to read json file using rapidjson and output to std::string?

Therefore I was really surprised that I can't just do something like this (with *.json file being in the same folder as my program):

rapidjson::Document d;
d.Parse("myJson.json");

My 1. question is:

Do I have to use std::ifstream and rapidjson::IStreamWrapper to get my Document like in the example above and what other as simple as possible alternatives there are?

My 2. question is: (this one would be much easier to ask if i could comment the post above)

What does the R mean in std::ifstream ifs { R"(C:\Test\Test.json)" }; and how do I change the C:\Test\Test.json string to const char* variable?

Because this isn't working.

const char* str = "C:\Test\Test.json";
std::ifstream ifs { R"(str)" }; //error
std::ifstream ifs { R(str) }; //error
std::ifstream ifs{ (str) }; //ok but I don't like it
[1]: https://rapidjson.org/md_doc_tutorial.html

Upvotes: 0

Views: 2177

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117831

You can use FileReadStream and ParseStream instead of the IStreamWrapper. According to the documentation, FileReadStream is much faster than IStreamWrapper.

The R means that it's a raw string literal. Without it, the backslashes are interpreted as the start of escape sequences and you would have to write it like this to make it correct:

"C:\\Test\\Test.json"

Or you could use forward slashes:

"C:/Test/Test.json"

Upvotes: 2

Related Questions