Accessing json data from .qrc file using std::ifstream and nlohmann json
-
wrote on 26 Apr 2024, 06:59 last edited by
I am trying to parse a json file, placed in the .qrc directory of my project. When I use QFile and QJsonDocument, and QJsonObject; it works fine. But, when I try to use std::ifstream and nlohmann::json, the file is not parsed.
Also, if::stream and nlohmann::json function parses the file if I give a hard coded path, instead of including the file in the .qrc folder of the project.
I am confident about the format of my json file.
So, is there any way to parse the json file, present in the .qrc directory using std::ifstream and nlohmann::json?This is how I am parsing the json data:
std::ifstream file1(jsonFilePath1); jsonObject1 = nlohmann::json::parse(file1);
This is the exception I am getting:
terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_3::detail::type_error'
what(): [json.exception.type_error.304] cannot use at() with null -
wrote on 26 Apr 2024, 07:03 last edited by Bonnie
Qrc files are only accessible by Qt classes. How should
ifstream
know how to read a qrc file?
You need to read the file using Qt classes and pass the content data to other classes. -
wrote on 26 Apr 2024, 07:10 last edited by
Hi @shreya_agrawal,
As @Bonnie said, only QFIle knows how to access files embedded via the Qt Resource System, so your options are:
- Use QFile::copy() to copy the file out of qrc, onto disk somewhere; or
- Use QFile to read the contents of the file, then pass the contents to
nlohmann::json::parse()
(there's an overload the accepts astd::string::iterator
, for example); or - If you really need to parse in a streaming mode, with
nlohmann::json
, then you'll need to use aQFile
wrapper that implementsstd::istream
; something like this: https://stackoverflow.com/questions/5204335/how-to-use-a-qfile-with-stdiostream#answers
Cheers.
-
Hi @shreya_agrawal,
As @Bonnie said, only QFIle knows how to access files embedded via the Qt Resource System, so your options are:
- Use QFile::copy() to copy the file out of qrc, onto disk somewhere; or
- Use QFile to read the contents of the file, then pass the contents to
nlohmann::json::parse()
(there's an overload the accepts astd::string::iterator
, for example); or - If you really need to parse in a streaming mode, with
nlohmann::json
, then you'll need to use aQFile
wrapper that implementsstd::istream
; something like this: https://stackoverflow.com/questions/5204335/how-to-use-a-qfile-with-stdiostream#answers
Cheers.
wrote on 26 Apr 2024, 07:16 last edited by@Paul-Colby
Thank you so much for such a detailed solution!
I think I would go with option 3 in my case. -
1/4