This question is not seeking a solution. But an explanation for the working solution.
The problem I had was to create a nested JSON where I get the hierarchy in a dot(.) separated formate.
example
Path: a.b.c.d
Value: 123
output should be
{
"A": {
"B": {
"C": {
"D": 123
}
}
}
}
Now I do have a working solution for this
import 'dart:convert';
Map<String, dynamic> mainJson = {};
void main() {
List<String> references = [
'A.B.C.D1',
'A.B1.C.D1',
'A.B2.C.D3',
];
for (var reference in references) {
enterValueForReference(reference, '123');
}
print(jsonEncode(mainJson));
}
enterValueForReference(String reference, dynamic value) {
List<String> nodes = reference.split(".").toList();
List<String> parentNodes = nodes.sublist(0, nodes.length - 1);
Map<String, dynamic> parentJson = {};
Map<String, dynamic> lastJson = {nodes.last: value};
parentJson = mainJson;
for (var node in parentNodes) {
if (parentJson.keys.contains(node) == false) {
parentJson[node] = Map<String, dynamic>();
}
parentJson = parentJson[node];
}
parentJson.addAll(lastJson);
}
I just don’t know how this is working. parentJson = mainJson;
this creates a reference between parentJson and mainJson but, parentJson = parentJson[node];
this should update the mainJson as well, right?
If anyone can make sense of the code, that would be helpful.