Trying to achieve this by using the following script, which I want to extend with a loop to loop through the input. This should filter on the objects with have the value "valse", the others should be deleted/replaced.
def Message processData(Message message) {
//getBody & new jsonSlurper
def body = message.getBody(java.lang.String) as String
def data = new JsonSlurper().parseText(body)
if (data.value != "false") {
body = body.replaceAll(~/^(.*?)\childNodes/, "")
message.setBody(body);
} else {
}
return message
}
Input:
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
Desired output:
[{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
CodePudding user response:
Assuming you have only a single child object every time and that your task is finding the first value=false
node and returning it with all the child nodes, you can do the following:
def processData(String message) {
def data = new JsonSlurper().parseText(message)[0]
while (data.value != 'false') { data = data.childNodes[0] }
return new JsonBuilder([data]).toPrettyString()
}
CodePudding user response:
import groovy.json.*
def body ='''
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
'''
def filter(arr){
for(i in arr){
if(i.value == 'false') return [i]
def filteredChild = filter(i.childNodes)
if(filteredChild)return filteredChild
}
return null // not found
}
def filtered = filter( new JsonSlurper().parseText(body) )
println new JsonBuilder(filtered).toPrettyString()