Reputation: 1431
I have an attribute called STATUS is in a JSON format, as follows:
{
"id":"343533",
"status":false,
"itemSize":0
}
I wuold like to be able to modify the itemSize value via a Groovy Execute script before it is passed onto another custom processor. I am struggling to find a way to solely modify the value for such key-value pair. I would like to be able to do something similar to the following where I loop through all key-value pairs and if the key has value zero then replace it to any numerical value. However, the below example only works with the top level attributes and does not allow modifying or removing a specific key-value pair in the attribute value.
def flowFile=session.get()
if(!flowFile)return
def zeroValueAttr = flowFile.getAttributes().findAll{it.value==0}.collect{it.key}
flowFile.removeAllAttributes(zeroValueAttr )
session.transfer(flowFile, REL_SUCCESS)
Can you help?
thank you
Upvotes: 0
Views: 1518
Reputation: 28564
the following code is for ExecuteGroovyScript
processor
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
def ff=session.get()
if(!ff)return
//read flow file content and parse it
def body = ff.read().withReader("UTF-8"){reader->
new JsonSlurper().parse(reader)
}
//replace some values
body.each{
if(it.value==0)it.value=123
}
//write new flow file content
ff.write("UTF-8"){writer->
new JsonBuilder(body).writeTo(writer)
}
//transfer
REL_SUCCESS << ff
Upvotes: 2