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