Search code examples
groovy

Remove empty Keys from JSON arrays using Groovy


I would like to remove the array SEO from the json when the keys "Description" and "Title" in the has no value.

json:

[
{
    "SEO": [
        {
            "Description": "",
            "Title": ""
        }
    ],
    "accesoires": [
        "1167296"
    ],
    "shortCode": "S-576",
    "spareParts": [
        "800236"
    ]
}]

I tried the below code but i'm not able to remove the array.

def Message processData(Message message) {
    def body = message.getBody(String);
    def json = new JsonSlurper().parseText(body)  


json.each{
  it.SEO.each{
      if(!(it.findResults{k, v -> v?.size() > 0 && v[0]?.length() > 0 ? v[0] : null })){
      json.remove("SEO")
      } } }


 def out= JsonOutput.toJson(json)


 message.setBody(out)
return message}

Solution

  • To remove the array "SEO" from the JSON when the keys "Description" and "Title" have no value, you can use the following Groovy code:

    def jsonString = '[{"SEO": [{"Description": "", "Title": ""}], "accesoires": ["1167296"], "shortCode": "S-576", "spareParts": ["800236"]}]'
    def json = new JsonSlurper().parseText(jsonString)
    
    for (item in json) {
      if (!item.SEO[0].Description && !item.SEO[0].Title) {
        item.remove('SEO')
      }
    }
    
    println(JsonOutput.toJson(json))
    

    This will first parse the JSON string into a list of maps using JsonSlurper. Then it iterates through each map in the list and checks if the "Description" and "Title" keys in the "SEO" array are empty. If they are, it removes the "SEO" array from the map using the remove() method. Finally, it prints the modified JSON using the JsonOutput.toJson() method.