Search code examples
groovyapache-nifiexecute-script

How to replace a value with another in json data in Groovy?


I am trying to replace API Data with "All" in Emp_Id field in data in json. And then make rows with every data of API.

API DATA: I have stored this data in "Response" attribute in ExtractText in Apache Nifi.

{
"status":"success",
"data":[[123,0],[124,0],[446,0],[617,1],[620,0],[470,1]]
}

//This API data is more, I have taken only 6 for reference but in real its almost 500-600
//(ignore 0 and 1 that is not required).

data:

{
"Emp_Id":"All",
"Emp_loc":"523",
"Emp_dept":"Management",
"Emp_sub_dept":"Finance",
"Emp_dept":"Accountant"
}

Expected Result

[
{
"Emp_Id":"123",
"Emp_loc":"523",
"Emp_dept":"Management",
"Emp_sub_dept":"Finance",
"Emp_dept":"Accountant"
},
{
"Emp_Id":"124",
"Emp_loc":"523",
"Emp_dept":"Management",
"Emp_sub_dept":"Finance",
"Emp_dept":"Accountant"
},
{
"Emp_Id":"446",
"Emp_loc":"523",
"Emp_dept":"Management",
"Emp_sub_dept":"Finance",
"Emp_dept":"Accountant"
},
{
"Emp_Id":"620",
"Emp_loc":"523",
"Emp_dept":"Management",
"Emp_sub_dept":"Finance",
"Emp_dept":"Accountant"
},
{
"Emp_Id":"470",
"Emp_loc":"523",
"Emp_dept":"Management",
"Emp_sub_dept":"Finance",
"Emp_dept":"Accountant"
}
]

This is tried in ecmaScript but I want it to be in groovy because these functions are not working in executeScript of NIFI and giving error."java.lang.assertionError: geberating bytecode". Or if any other approach for converting this data.

const response = {
    "status": "success",
    "data": [[123, 0], [124, 0], [446, 0], [617, 1], [620, 0], [470 ,1]]
};

const template = {
    "Emp_Id": "All",
    "Emp_loc": 523,
    "Emp_dept": "Management",
    "Emp_sub_dept": "Finance",
    "Emp_dept": "Accountant"
};

const result = response.data.map(([id]) =>
    Object.fromEntries(Object.entries(template).map(([k, v]) =>
        [k, v === "All" ? id : v]
    ))
);
    
console.log(result);

Solution

  • import groovy.json.JsonBuilder
    
    def response = [
        "status": "success",
        "data": [[123, 0], [124, 0], [446, 0], [617, 1], [620, 0], [470 ,1]]
    ]
    
    def template = [
        "Emp_Id": "All",
        "Emp_loc": 523,
        "Emp_dept": "Management",
        "Emp_sub_dept": "Finance",
        "Emp_dept": "Accountant"
    ]
    
    def result = response.data.collect{ i -> 
            template.collectEntries{ k,v -> 
                [k, v=="All" ? i[0] : v] 
            } 
        }
     
    println new JsonBuilder(result).toPrettyString()
    

    https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Map.html#collectEntries(groovy.lang.Closure)

    https://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#collect(groovy.lang.Closure)