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

How to parse multiple same Keys of JSON and save them? #612

Closed
cybercitizen7 opened this issue Jun 8, 2017 · 3 comments
Closed

How to parse multiple same Keys of JSON and save them? #612

cybercitizen7 opened this issue Jun 8, 2017 · 3 comments

Comments

@cybercitizen7
Copy link

cybercitizen7 commented Jun 8, 2017

Hey guys,

This is NOT AN ISSUE, but Niels told me to put my question here anyway.

I have several Objects in my JSON, something like this:

 {
  Id= 1
  Name = David
},
{
  Id = 2
  Name = Katja
},
{
  Id = 3
  Name = Luka
},

..

As you can see, I have several identifiers (Id, Name) which are the same in my JSON. How can I do this in C++ with this Lib, so that I can parse it only once and store it somewhere for future use?

E.g. I want to populate a List of Users on my GUI. And then also track which User was clicked and call get that Id from JSON (there are more data in JSON than Id and Name).

@nlohmann
Copy link
Owner

nlohmann commented Jun 8, 2017

What about the following:

#include "json.hpp"
#include <unordered_map>

using json = nlohmann::json;

int main()
{
    // the JSON text
    std::string s = R"([
        {"id": 1, "name": "David"},
        {"id": 2, "name": "Katja"},
        {"id": 3, "name": "Luka"}
    ])";
    
    // create a JSON value
    json j = json::parse(s);
    std::cout << j << std::endl;
    
    // some lookup container
    std::unordered_map<int, json> lookup;
    
    // add elements from the JSON value to the lookup container
    for (auto &el : j)
    {
        lookup[el["id"]] = el;
    }
    
    // lookup
    std::cout << lookup[2] << std::endl;
}

@nlohmann
Copy link
Owner

Hey @dk1206, does this work for you?

@cybercitizen7
Copy link
Author

I will work on it later, as this requires some other knowledge of c++, which I currently do not have.

I will close this issue for now.

Thanks for help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants