Reputation: 51
In Groovy, I am trying to filter a Map whereby I specifically want to check if any occurrence of cars.models.colors
is empty. If it is, I want to remove this particular element.
For example, I expect to remove:
{
"name": "m5",
"colors": []
}
Code:
#!/usr/local/bin/groovy
import groovy.json.*
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText '''
{
"cars": [{
"name": "ford",
"models": [{
"name": "fiesta",
"colors": [
{ "colorName": "grey", "colorId": "123" },
{ "colorName": "white", "colorId": "844" },
{ "colorName": "green", "colorId": "901" }
]
}]
}, {
"name": "vw",
"models": [{
"name": "golf",
"colors": [{ "colorName": "black", "colorId": "392" }]
}]
}, {
"name": "bmw",
"models": [{
"name": "m5",
"colors": []
}]
}
]
}
'''
Map filtered = [:]
filtered['root'] = object.cars.models.colors.findAll {it.value.isEmpty()}
println JsonOutput.prettyPrint(JsonOutput.toJson(filtered))
Once the filtering has been successfully applied, I am expecting the JSON to look such as
{
"cars": [{
"name": "ford",
"models": [{
"name": "fiesta",
"colors": [{
"colorName": "grey",
"colorId": "123"
},
{
"colorName": "white",
"colorId": "844"
},
{
"colorName": "green",
"colorId": "901"
}
]
}]
},
{
"name": "vw",
"models": [{
"name": "golf",
"colors": [{
"colorName": "black",
"colorId": "392"
}]
}]
},
{
"name": "bmw",
"models": []
}
]
}
However, my code currently just returns:
{
"root": [
[
]
]
}
Upvotes: 0
Views: 1551
Reputation: 37033
Since you loaded JSON is already a "copy" of the orignal, you can just work on the loaded object
(directly manipulate it).
So you can iterate the cars and filter out all models without color. E.g.
import groovy.json.*
def object = new JsonSlurper().parseText('''
{
"cars": [{
"name": "ford",
"models": [{
"name": "fiesta",
"colors": [
{ "colorName": "grey", "colorId": "123" },
{ "colorName": "white", "colorId": "844" },
{ "colorName": "green", "colorId": "901" }
]
}]
}, {
"name": "bmw",
"models": [{"name": "m5","colors": []}]
}]
}
''')
object.cars.each{
it.models = it.models.findAll{ it.colors }
}
println JsonOutput.prettyPrint(JsonOutput.toJson(object))
Upvotes: 1