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

Reading and writing array elements #1607

Closed
kamocio opened this issue May 23, 2019 · 5 comments
Closed

Reading and writing array elements #1607

kamocio opened this issue May 23, 2019 · 5 comments

Comments

@kamocio
Copy link

kamocio commented May 23, 2019

Say I am given a JSON:

{
"name": "John Doe",
"meals":
[
{
"breakfast": "omlet at 8AM"
},
{
"lunch": "salad at 12"
}
]
}

And its loaded into below object(does not matter how):

nlohmann::json someJson;

Now I'd like to load the "meals" structure into some STL container.

std::? = someJson["meals"];

I also need to be able to make some changes to the values and write it back.

someJson["meals"] = ?;

How would that look like? Struggling to figure out the type(s) to use here.

@nickaein
Copy link
Contributor

The library already provides STL-like access APIs for reading/writing JSON values. Do they cover your requirements?

@kamocio
Copy link
Author

kamocio commented May 23, 2019

Thanks, that's what I've been trying to figure out. I'm not able to "fit" any STL container to the JSON format I listed above.

Finding an STL container (even if its a nested, complicated one) that would allow reading/writing of "meals" element is what this question is about.

@kamocio
Copy link
Author

kamocio commented May 23, 2019

It appears that the STL structure would be:
vector<map<string, string>>

I was able to make it work like that, though the c++ code of adding/searching elements is quite ugly (nothing to do with the library, just a weird JSON doc format). I'll close this.

@kamocio kamocio closed this as completed May 23, 2019
@nickaein
Copy link
Contributor

It appears that the STL structure would be:
vector<map<string, string>>

The underlying data type is std::map<std::string, basic_json>> for JSON objects and std::vector<basic_json> for JSON arrays, by default. (More info here and here).

though the c++ code of adding/searching elements is quite ugly (nothing to do with the library, just a weird JSON doc format). I'll close this.

Correct. JSON schema has a great impact on ease of implementation . I've written a sample demo based on your schema: https://wandbox.org/permlink/iVUmUQV1GDtXzr6Q

You can find more info at README page and indeed the documentations.

@kamocio
Copy link
Author

kamocio commented May 24, 2019

Thanks!

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

No branches or pull requests

2 participants