简体   繁体   中英

groovy filter fields in json response

I'm trying to filter out some fields in my JSON response. Sample response below:

{
  "Status": "Fail",
  "Code": "500",
  "Rules": [{
      "Status": "Fail",
      "Message": "Code error",
      "id": "123456"
    },
    {
      "Status": "Fail",
      "Message": "Configuration error",
      "id": "12345"
    }
  ]
}

I want to omit code and id fields and print rest of the fields in JSON. the final response should look like this:-

{
  "Status": "Fail",
  "Rules": [{
      "Status": "Fail",
      "Message": "Code error"
    },
    {
      "Status": "Fail",
      "Message": "Configuration error"
    }
  ]
}

Any idea on how we can achieve it?

Groovy already provide classes and mechanisms to do this, first you need to import class groovy.json.JsonGenerator

Then you can define the fields that you want to ignore from serilization:

def generator = new JsonGenerator.Options()
    .excludeFieldsByName('id', 'Code')
    .build()

And finally just need to parse the output:

String output = generator.toJson(input)

The output will look something like this:

{
    "Status": "Fail",
    "Rules": [
        {
            "Status": "Fail",
            "Message": "Code error"
        },
        {
            "Status": "Fail",
            "Message": "Configuration error"
        }
    ]
}

Here is a full sample of how I did this:

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

String json = '''{
  "Status": "Fail",
  "Code": "500",
  "Rules": [{
      "Status": "Fail",
      "Message": "Code error",
      "id": "123456"
    },
    {
      "Status": "Fail",
      "Message": "Configuration error",
      "id": "12345"
    }
  ]
}'''

Map input = new JsonSlurper().parseText(json)

def generator = new JsonGenerator.Options()
    .excludeFieldsByName('id', 'Code')
    .build()

String output = generator.toJson(input)

println JsonOutput.prettyPrint(output)

To see more configurations for this JsonGenerator class you can go to official documentation here: https://groovy-lang.org/json.html#_customizing_output

 var getData = { "Status": "Fail", "Code": "500", "Rules": [{ "Status": "Fail", "Message": "Code error", "id": "123456" }, { "Status": "Fail", "Message": "Configuration error", "id": "12345" } ] }; delete getData.Code; for (var i = 0; i < getData.Rules.length; i++) { delete getData.Rules[i].id; } console.log(getData);

Note:- You can simply use delete elementValue to achieve that

 const obj = { "Status": "Fail", "Code": "500", "Rules": [ { "Status": "Fail", "Message": "Code error", "id": "123456" }, { "Status": "Fail", "Message": "Configuration error", "id": "12345" } ] } const result = Object.keys(obj).reduce((acc, curr) => { if (curr.== "Code") { acc = {..,acc: [curr]. obj[curr] } } if (curr === "Rules") { acc = {..,acc: [curr]. obj[curr].map(rule => { delete rule,id return rule }) } } return acc }. {}) console.log(result)

A solution which recursively walks through your json and removes specific fields on any depth:

import groovy.json.*

def str = '''
{
  "Status": "Fail",
  "Code": "500",
  "Rules": [{
      "Status": "Fail",
      "Message": "Code error",
      "id": "123456"
    },
    {
      "Status": "Fail",
      "Message": "Configuration error",
      "id": "12345"
    }
  ]
}'''

def json  = new JsonSlurper().parseText(str)
def clean = recursivelyRemove(json, ['id', 'Code'])

println JsonOutput.prettyPrint(JsonOutput.toJson(clean))

def recursivelyRemove(obj, fieldNames) {
  switch(obj) {
    case Map:
      obj.findAll { k, v -> 
        !(k in fieldNames)
      }.collectEntries { k, v -> 
        [k, recursivelyRemove(v, fieldNames)]
      }
      break
    case List:
      obj.collect { recursivelyRemove(it, fieldNames) }
      break
    default: 
      obj
  }
}

which prints:


─➤ groovy solution.groovy                                                                                              1 ↵
{
    "Status": "Fail",
    "Rules": [
        {
            "Status": "Fail",
            "Message": "Code error"
        },
        {
            "Status": "Fail",
            "Message": "Configuration error"
        }
    ]
}

when run.

This has the upside that it is not hard-coded to your json structure, ie if the structure changes for some reason, this code might still work.

A potential downside is that if your json structure is very deep (say hundreds or thousands of levels of nesting), you might get a StackOverflowException as we are making recursive calls. This might or might not be likely depending on your scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM