โ03-29-2022 04:56 AM
Hello there,
Is there a way to flatten a nested JSON (multiple objects inside objects/arrays) without using a Script Snap?
Take this input for example:
{
"msg":"Hello, World",
"num":1,
"fruits":{
"apple":1,
"orange":4,
"inner2":{
"message":"found"
},
"cars":[
"bmw",
"audi",
"dacia"
],
"cars2":[
{
"bmw":"something"
},
{
"audi":"else"
}
]
}
}
The output should look like this:
{
"msg": "Hello, World",
"fruits.cars2.1.audi": "else",
"fruits.orange": 4,
"num": 1,
"fruits.cars.1": "audi",
"fruits.cars.0": "bmw",
"fruits.apple": 1,
"fruits.cars.2": "dacia",
"fruits.inner2.message": "found",
"fruits.cars2.0.bmw": "something"
}
So every key name is constructed from the inner objects/arrays of key names delimited with โ.โ in the case of objects. In the case of arrays, the key name should also have the index number of the current item.
One way to do this is using the script snap using any available language. A function that loops through the root object and check the type of the current property. If itโs of type Object or array then I can call the function again.
Iโve tried using expression libraries but with no luck.
Any ideas?
2 weeks ago
Any luck on this? I am trying to find a solution for a similar problem
2 weeks ago - last edited 2 weeks ago
There is the AutoPrep snap that can handle this transformation. Do you have access to that?
https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/2568781882/AutoPrep
2 weeks ago
Wow! That's a powerful snap! Worked like a charm for my use case.
Thank you for the suggestion.
2 weeks ago
Indeed it is! This snap can flatten structures, split columns, mask data, rename columns, handle nulls, and more, much faster than relying on python or expressions.