Apache NiFi - JOLT Expression: Flatten Hierarchical Data & Distribute Value from JSON into Array of Objects
Hi Folks,
This is likely a multipart problem, but I've been trying to get the following sample JSON to distribute the "id" value from the root of the JSON object into a flattened array of objects with the "id" value and the "code" value from each category (or subcategory in the nested structure). For example, given the following JSON payload:
{
"id": "1234",
"categories": [
{
"code": "A",
"name": "Alpha",
"subcategories": [
{
"code": "AA",
"name": "Alpha Alpha"
},
{
"code": "AB",
"name": "Alpha Bravo"
}
]
},
{
"code": "B",
"name": "Bravo"
},
{
"code": "C",
"name": "Charlie"
},
{
"code": "D",
"name": "Delta"
}
]
}
The Desired Output would be:
[
{
"individualId": "1234",
"categoryCode": "A",
"categoryName": "Alpha"
},
{
"individualId": "1234",
"categoryCode": "AA",
"categoryName": "Alpha Alpha"
},
{
"individualId": "1234",
"categoryCode": "AB",
"categoryName": "Alpha Bravo"
},
{
"individualId": "1234",
"categoryCode": "B",
"categoryName": "Bravo"
},
{
"individualId": "1234",
"categoryCode": "C",
"categoryName": "Charlie"
},
{
"individualId": "1234",
"categoryCode": "D",
"categoryName": "Delta"
}
]
I tried the following JOLT Transformation Expression:
[
{
"operation": "shift",
"spec": {
"id": "id",
"categories": {
"*": {
"code": "categories[&1].categoryCode",
"name": "categories[&1].categoryName",
"@(2,id)": "categories[&1].individualId",
"subcategories": {
"*": {
"code": "categories[&3].categoryCode",
"name": "categories[&3].categoryName",
"@(4,id)": "categories[&3].individualId"
}
}
}
}
}
},
{
"operation": "shift",
"spec": {
"categories": {
"*": "[]"
}
}
}
]
But got this, not sure why the subcategories keep getting grouped into the first element,. Any insight or help would be much appreciated:
[ {
"individualId" : [ "1234", "1234", "1234" ],
"categoryCode" : [ "A", "AA", "AB" ],
"categoryName" : [ "Alpha", "Alpha Alpha", "Alpha Bravo" ]
}, {
"individualId" : "1234",
"categoryCode" : "B",
"categoryName" : "Bravo"
}, {
"individualId" : "1234",
"categoryCode" : "C",
"categoryName" : "Charlie"
}, {
"individualId" : "1234",
"categoryCode" : "D",
"categoryName" : "Delta"
} ]

