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?
03-13-2024 07:57 AM
Any luck on this? I am trying to find a solution for a similar problem
03-14-2024 07:05 AM - edited 03-14-2024 07:05 AM
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
03-14-2024 09:45 AM
Wow! That's a powerful snap! Worked like a charm for my use case.
Thank you for the suggestion.
03-15-2024 12:11 PM
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.