Hi Team,
Need help. I have below two part.
1. merge the original Response with the API Response
Original response
[{
"code": "100016",
"Date": "2022-09-22"
}, {
"code": "100017",
"Date": "2022-09-02"
},
{
"code": "100018",
"Date": "2022-09-02"
},
{
"code": "100019",
"Date": "2022-09-02"
}
]
API Response:
[{
"Record": "Record 3",
"Description": "Processing failed due Internal Server Error."
}, {
"Record": "Record 4",
"Description": "Processing failed due to error in record: 3"
}]
Required output:
{
"RequestPayload": [{
"code": "100016",
"Date": "2022-09-22"
}, {
"code": "100017",
"Date": "2022-09-02"
},
{
"code": "100018",
"Date": "2022-09-02"
},
{
"code": "100019",
"Date": "2022-09-02"
}
],
"ApiResponse": [{
"Record": "Record 3",
"Description": "Processing failed due Internal Server Error."
}, {
"Record": "Record 4",
"Description": "Processing failed due to error in record: 3"
}]
}
After getting the above output I need to mapped the json objects as below
input:
{
"RequestPayload": [{
"code": "100016",
"Date": "2022-09-22"
}, {
"code": "100017",
"Date": "2022-09-02"
},
{
"code": "100018",
"Date": "2022-09-02"
},
{
"code": "100019",
"Date": "2022-09-02"
}
],
"ApiResponse": [{
"Record": "Record 3",
"Description": "Processing failed due Internal Server Error."
}, {
"Record": "Record 4",
"Description": "Processing failed due to error in record: 3"
}]
}
I am getting below output:
[
"{\"code\":\"100018\",\"Date\":\"2022-09-22\"}",
"{\"code\":\"100019\",\"Date\":\"2022-09-02\"}"
]
Expected Output:
[{
"code": "100018",
"Date": "2022-09-22",
"Record": "Record 3",
"Description": "Processing failed due Internal Server Error."."
}, {
"code": "100019",
"Date": "2022-09-02",
"Record": "Record 4",
"Description": "Processing failed due to error in record: 3"
}
]
For that I am using below groovy Script:
import org.apache.commons.io.IOUtils
import java.nio.charset.StandardCharsets
import groovy.json.*
import java.util.ArrayList
def flowFile = session.get()
if(!flowFile) return
try {
flowFile = session.write(flowFile,
{ inputStream, outputStream ->
def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
def obj = new JsonSlurper().parseText(text)
def final1 = []
int j = obj.RequestPayload.size()
for (int i=0;i<j;i++){
index = i+1
def rec = 'Record ' + index
if (rec in obj.ApiResponse.Record){
final1.add(JsonOutput.toJson(obj.RequestPayload[i]))
}
}
def response1 = JsonOutput.toJson(final1)
outputStream.write(JsonOutput.prettyPrint(response1).getBytes(StandardCharsets.UTF_8))
} as StreamCallback)
session.transfer(flowFile, REL_SUCCESS)
} catch(Exception e) {
log.error('Error during JSON operations', e)
session.transfer(flowFile, REL_FAILURE)
}
Can you please help. I am not familiar with groovy but i want to get the desired output with groovy script. Thanks in Advance