Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sub-array to vector or map object? #1870

Closed
flamendless opened this issue Dec 14, 2019 · 5 comments
Closed

Sub-array to vector or map object? #1870

flamendless opened this issue Dec 14, 2019 · 5 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@flamendless
Copy link

flamendless commented Dec 14, 2019

Hi, how do I store the result of
?? flags = parsed.at("flags");

Into a std::map or std::vector so that I can loop them.

With this .json file:

{
  "width": 640, "height": 480,
  "flags": {
    "Ph": 1, "En": 0, "Fr": 1
  }
}

Specifically i want to for-loop on the ?? return type and have access to the strings (i.e "Ph", "En", etc) and the associated values

I don't want to use auto

Sent from my HUAWEI GR5 2017 using FastHub

@flamendless flamendless changed the title Return type of a sub-array Sub-array to vector or map object? Dec 14, 2019
@sonulohani
Copy link
Contributor

sonulohani commented Dec 14, 2019

Here is the way to store the result in std::map.

#include "../single_include/nlohmann/json.hpp"
#include <iostream>

int main()
{
    const nlohmann::json j = {{"width", 640}, {"height", 480}, {"flags", {{"Ph", 1}, {"En", 0}, {"Fr", 1}}}};

    std::map<std::string, uint32_t> m;

    j.at("flags").get_to(m);
    for (const auto &i : m)
    {
        std::cout << i.first << " " << i.second << '\n';
    }

    return 0;
}

@nickaein
Copy link
Contributor

Similar to @sonulohani solution, here is a working example without the use of auto: https://wandbox.org/permlink/HkBwBfWkS6waerF3

BTW, is there any reason to avoid that? Using auto in this case can make the code much cleaner. Given that this library needs C++11 support, the auto should be available nevertheless.

@flamendless
Copy link
Author

@sonulohani thank you for this solution.

Sent from my HUAWEI GR5 2017 using FastHub

@flamendless
Copy link
Author

@nickaein indeed, using auto is clean, but im still learning c++ so for now i want to do it the old way

Sent from my HUAWEI GR5 2017 using FastHub

@nlohmann
Copy link
Owner

The return value of at is a reference (json&).

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Dec 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

4 participants