cancel
Showing results for 
Search instead for 
Did you mean: 

JSON Formatting and Merging

philliperamos
Contributor

Hello All,
I have encountered a scenario where we need to map all the element with key, “tree”, to a single array of the same name. I have provided an example below
Input:

[{
“tree”: {
“name”: “DB1”
“type”: “database”
“children”: [{
“name”: “SCHA”
“type”: “schema”
“children”: [{
“name”: “TABLEA”
“type”: “table”
“leaves”: [{
“name”: “COA”,
“type”: “column”
}, {
“name”: “COB”,
“type”: “column”
}, {
“name”: “COC”,
“type”: “column”
}]
}]
}]
},
{
“tree”: {
“name”: “DB2”
“type”: “database”
“children”: [{
“name”: “SCHB”
“type”: “schema”
“children”: [{
“name”: “TABLEB”
“type”: “table”
“leaves”: [{
“name”: “CO1”,
“type”: “column”
}, {
“name”: “CO2”,
“type”: “column”
}, {
“name”: “CO3”,
“type”: “column”
}]
}]
}]
}
}
}]

Intended output:

{
“tree”: [{
“name”: “DB1”
“type”: “database”
“children”: [{
“name”: “SCHA”
“type”: “schema”
“children”: [{
“name”: “TABLE1”
“type”: “table”
“leaves”: [{
“name”: “CO1”,
“type”: “column”
}, {
“name”: “CO2”,
“type”: “column”
}, {
“name”: “CO3”,
“type”: “column”
}]
}]
}]
}, {

    "name": "DB2"
    "type": "database"
    "children": [{
        "name": "SCHB"
        "type": "schema"
        "children": [{
            "name": "TABLE1"
            "type": "table"
            "leaves": [{
                "name": "CO1",
                "type": "column"
            }, {
                "name": "CO2",
                "type": "column"
            }, {
                "name": "CO3",
                "type": "column"
            }]
        }]
    }]
}]

}

Essentially, instead of having individual objects with the name tree we are trying to create a single tree array with all the data inside. Any suggestions on this would be really helpful.
Thank you.

1 REPLY 1

cjhoward18
Employee
Employee

Assuming your input is a single document with an array of objects, rather than a stream of individual documents.

With that assumption you can use a mapper with the expression:
jsonPath($, "$[*].tree") and target path: tree

This will collect all tree objects from every element in the array, then write that list to the target path tree