-
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
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 create an array of Objects? #470
Comments
Yes, please have a look at the documentation: https://github.com/nlohmann/json#json-as-first-class-data-type |
json j = {
{ "objects" , {
{ "object" , {
{ "address", "adr1" },
}, },
{ "object" , {
{ "address", "adr2" },
}, },
{ "object" , {
{ "address", "adr3" },
}, },
},
}; |
Yes. Just like auto jsonObjects = json::array();
for(auto i = 0; i <= 5; ++i) {
jsonObjects.push_back(json::object());
} |
Of course - it uses (more or less) the same API as |
Thanks everyone. |
Excellent. Would it be common enough to get mentioned in the main README doc? Would have helped me I know. Thanks nlohmann, love the class. |
hi I am new to C++ and I am trying to achieve the same thing here. Can anyone provide sample code for this problem? Thank you in advance. |
Can you please tell how to iterate over this type of json array ? {
"objects": [
{
"object": {
"address": "xxx"
}
},
{
"object": {
"address": "xxx"
}
},
{
"object": {
"address": "xxx"
}
}
]
} |
// assuming you parse the JSON above to variable j
for (const auto& element : j["objects"])
{
std::cout << element << std::endl;
} This should output
Inside the loop, you can access the other elements with element["object"]["address"] |
Thanks! |
Hi,
Now I would like to accessand modify a specific element of
but they crash and probably I have misunderstood the documentation. |
The example you posted ins not valid JSON - there are commas missing. However, if you pass strings to |
Thanks for the fast answer, and you are right, the Json was not valid as written but I just wrote it by hand to give an overview of what I was doing (I edited, should be fine now). In the begin my objective was to access a specific element in an array, which I'm sure is present but I don't know the position, by using the underlying search/find features (like those used by In the end I realized that what I was trying is not possible so find out some option:
But from information gatered seems I should scan the array twice, first time to find the position comparing the key, then again to modify the value. Still testing, as soon as I find the solution I will post it. |
I've got what I was doing wrong and for sure I have to learn/deal more about APIs return values and how they work.
maybe there is a clean/better way to do it because it seems a little bit ugly to me. In my humble opinion the |
Its possible to create the folowing structure?
Using something like jsonObject["objects"]["object"]
The text was updated successfully, but these errors were encountered: