-
Suppose my .json file looks something like this: {
"/post_one": {
"user_one": "sakfjsaljfjoijfoisadjfio@#42asdf",
"user_two": "dfasfjlsjldkjfl;ksjadflkj@#42asdf"
},
"/post_two": {
"user_foo": "sakfjsaljfjoijfoisadjfio@@$2asdf",
"user_bar": "sakfjsaljfjoijfoisadjfio@#%#5324"
}
} I will be parsing this structure into an |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
The Example: #include "json.hpp"
using json = nlohmann::json;
int main()
{
json j = R"({
"/post_one": {
"user_one": "sakfjsaljfjoijfoisadjfio@#42asdf",
"user_two": "dfasfjlsjldkjfl;ksjadflkj@#42asdf"
},
"/post_two": {
"user_foo": "sakfjsaljfjoijfoisadjfio@@$2asdf",
"user_bar": "sakfjsaljfjoijfoisadjfio@#%#5324"
}
})"_json;
std::unordered_map<std::string, std::vector<std::pair<std::string, std::string>>> m;
for (const auto & outer : j.items())
{
for (const auto & inner : outer.value().items())
{
m[outer.key()].emplace_back(inner.key(), inner.value());
}
}
} |
Beta Was this translation helpful? Give feedback.
-
@nlohmann OK, I marked it too early. Looks like this solution Does Not work for me. std::ifstream cred_stream{JSON_FILE_NAME};
std::string file_data;
if(cred_stream.is_open()){
std::string line;
while(std::getline(cred_stream, line)){
file_data.append(line);
}
}else{
perror("Unable to open API auth file for REST services\n");
::exit(1);
}
cred_stream.close();
nlohmann::json json_reader(file_data);
for(const auto& endpoints : json_reader.items()){
for(const auto& credentials : endpoints.value().items()){
std::cout << credentials.value() << std::endl;
this->_endpoint_cred_map[endpoints.key()].emplace_back(credentials.key(), credentials.value());
}
} But, when I try to print this out, the whole JSON file is dumped into |
Beta Was this translation helpful? Give feedback.
The
items()
function should do the job.Example: