Open samer1977 opened 5 months ago
This is not my original code, I stole it from here.
I changed it very lightly, it is not exactly what you want, because it does not process arrays, yet.
See the unchanged z3
array below.
At any rate, here it is:
// JSLT transform which flattens nested objects into flat objects
// { "a": { "b": 1 } } => { "a.b": 1 }
def flatten-object (obj)
let flat = { for ($obj) .key : .value if (not (is-object (.value))) }
let nested = [
for ($obj)
let outerkey = (.key)
[for (flatten-object (array (.value))) {
"key": $outerkey + "." + .key,
"value": if (is-object (.value)) flatten-object (.value) else .value
}]
if (is-object (.value))
]
let flattened = (flatten ($nested))
{ for ($flattened) .key : .value } + $flat
flatten-object (.)
This transformation produces for the input above this result:
{
"x" : "x1",
"y" : "y2",
"z.z1" : "z11",
"z.z3" : [ 1, {
"zzz" : "skid",
"zzz1" : null
}, 2 ]
}
Hi, I noticed the flatten-objects function here doesnt flatten nested arrays. I understand that flattening can have different meaning & expectations depending on each use case but my expectation when I want to flatten a json that it should cover everything. Of course considering arrays can get very complex given what arrays can hold. Part of learning jslt I wanted to take on this challenge to see if it can be done. I hope I was successful but part of doing this I found myself using some other helpful functions (see comments on each function) that I thought it might be nice to have not just for flattening but for other things and maybe have them as built function. Without further due , here is the code:
Example:
Output:
I appreciate any well explained feedback. Thanks S