-
-
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
dynamically constructing an arbitrarily nested object #114
Comments
Hi @nlohmann, I had a look at that before I raised this and I didn't quite think so. It felt almost like the opposite. Say someone sends me this: {
"a.b.c" : {
"values" : [1,2,..,n]
}
} When I receive that in C++, I want to take it and end up with something similar to: {
"a" : {
"b" : {
"c" : 1|2|3...|n
}
}
} For my use case, I'm being told the structure of the JSON the user requires and the possible values. I'm then generating the values based on a number of rules. The trouble is, when I generate the first outer object "a", I can't seem to add b and then c inside it to create the structure in my second example above. |
I still do not really know what kind of extension you have in mind. I will not change the parser to process non-standard JSON, because I want the library to be standard compliant. |
It wouldn't be non-standard JSON, my example above was just for illustration the value of "c" would be a standard JSON array of numbers separated by commas. I don't remember the exact details to be honest. The company has paused the project so it's unlikely I'll need to do this anymore. If the below doesn't clarify what I meant then I'm not sure how else to explain so feel free to close. I was writing a test tool, this particular component was a data generator. The generator would get sent a description of the JSON structure it should create. If a field name is received as "a.b.c" it would need to create a nested JSON object as described in my previous response (with a standard [1,2,3...,n] JSON array). From what I remember, after I created an object a, I then created the next object b. My intitial intuition was that this should work: auto record(nlohmann::json({});
nlohmann::json field = record;
for (const auto &part:utils::spilt(name)) {
field = field[part].is_null() ? nlohmann::json({}) : field[part];
} i.e. I start by creating an empty object {}. Given the key a.b.c, I split that into a b and c respectively. |
OK, now I understand. It seems to be a very narrow use case, and I am not sure whether it could be helpful to anyone else. (Let's hope this includes you ;-)) Thanks for clarifying! |
How would you go about constructing an arbitrarily nested object e.g. a.b.c.d for serialisation?
Something like the following comes to mind but doesn't work:
where split(...) returns a vector of components from a dot notation string.
I know I can do
record["a"]["b"]["c"]
but they keys or depth aren't known in advance.The text was updated successfully, but these errors were encountered: