Home > Software engineering >  Groovy remove list if an item is equal to
Groovy remove list if an item is equal to

Time:10-26

I have this json:

{
    "books": [
        {
            "bookId": "1",
            "bookName": "name1",
            "bookYear": "2010"
        },
        {
            "bookId": "2",
            "bookName": "name2",
            "bookYear": "2010"
        }
    ]
}

and I want to remove the list that contains "bookId": "1" The result should be:

{
    "books": [
        {
            "bookId": "2",
            "bookName": "name2",
            "bookYear": "2010"
        }
    ]
}

I've tried this code:

import groovy.json.JsonSlurper
import groovy.json.JsonOutput


JsonSlurper slurper = new JsonSlurper()
String jsonString = vars.get("jsonOutput")
def parsedJson = slurper.parseText(jsonString)

log.info("Json before: "   jsonString)

int num = parsedJson.books.size()
for(int i=0;i<parsedJson.books.size();i  ){
    parsedJson.books[i].values().removeAll(value -> value.equals("1"))
}

def json = JsonOutput.toJson(parsedJson)
log.info("Json after: "   json.toString())

but it removes only the "bookId" from list:

Json before: {"books":[{"bookId":"1","bookName":"name1","bookYear":"2010"},{"bookId":"2","bookName":"name2","bookYear":"2010"}]}

Json after: {"books":[{"bookName":"name1","bookYear":"2010"},{"bookId":"2","bookName":"name2","bookYear":"2010"}]}

Please, could you help me on that?

CodePudding user response:

You can filter the list of books like so:

def parsedJson = slurper.parseText(jsonString)

parsedJson.books = parsedJson.books.findAll { it.bookId != '1' }

def json = JsonOutput.toJson(parsedJson)
  • Related