I'm currently trying to display Json data into a Material Tree , the problem is that the material tree won't directly take a Json dataSource and i need to convert mine to something like this :
[
{
name: 'Fruit',
children: [
{name: 'Apple'},
{name: 'Banana'},
{name: 'Fruit loops'},
]
}, {
name: 'Vegetables',
children: [
{
name: 'Green',
children: [
{name: 'Broccoli'},
{name: 'Brussel sprouts'},
]
}
]
},
];
The json data look like this :
{
"processTimer": {
"Environment": {
"Environment": {
"initiator": {
"commonName": "anonymous"
},
"locale": "fr_FR",
"counter": "9004",
"last-fault": {
"type": "FaultException",
"message": "java.lang.NullPointerException",
}
}
}
{"oui" : {
"_uri": "",
"__text" : ""
}
}
}
}
After weeks of search i understood that i would need a recursive function that take incoming json and traverse it throught to rebuild the new object. But i don't really get how do i get all the keys and transform them into values. I tried a lot of different StackOverflow code but i couldn't find one that does what i need.
I reseigned on using ngx-json-viewer for now even tho it's not the sexiest it takes directly json format in, i still wonder why most of the javascript Tree libraries don't.
If someone found something or want to give me a hand it would be greatly appreciated.
Thanks in advance ! :)
Edit: i Found this method on this thread that help me to navigate the object :
traverse(jsonObj) {
if (jsonObj !== null && typeof jsonObj == "object") {
Object.entries(jsonObj).forEach(([key, value]) => {
// If value is an object (This means that the value is a child) and is the same as a variable
//(because the first key is always the processName)
if (typeof value == "object" && key == this.processName) {
this.treeObject.push({ name: key, children: [] })
this.traverse(value)
//If value is an object (This means that the value is a child)
} else if (typeof value == "object") {
this.treeObject[0].children.push({ name: key, children: [] })
this.traverse(value)
// If value is a real value
} else if (typeof value != "object") {
this.treeObject[0].children.push({ name: key, value: value })
}
});
}
}
The problem is that i don't know how to go deeper into the TreeObject at the same time as i'm going deeper in the JsonObj, how to keep track of the level, because right now it obviously push each item in the first array after the processName like this :
[{…}]
0: name: "ProcessTimer"
children: Array(25)
0: {name: "Environment", children: Array(0)}
1: {name: "_uri", children: Array(1)}
2: {name: "Environment", children: Array(0)}
...
...
23: {name: "_uri", children: Array(1)}
24: {name: "__text", children: Array(1)}
Thanks for any help !