简体   繁体   English

json 响应中的 groovy 过滤字段

[英]groovy filter fields in json response

I'm trying to filter out some fields in my JSON response.我正在尝试过滤掉我的 JSON 响应中的一些字段。 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.我想省略代码和 id 字段并打印 JSON 中字段的 rest。 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 Groovy 已经提供了类和机制来做到这一点,首先你需要导入 class groovy.Z466DEEC76ECDF2345FCA6D38ZJ571F6

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:最后只需要解析output:

String output = generator.toJson(input)

The output will look something like this: output 看起来像这样:

{
    "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要查看此JsonGenerator class 的更多配置,您可以 go 到此处的官方文档: https://groovy-lang.org/json.html#_customizing

 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注意:- 您可以简单地使用delete elementValue来实现

 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:递归遍历您的 json 并删除任何深度的特定字段的解决方案:

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.这样做的好处是它没有硬编码到您的 json 结构中,即如果结构由于某种原因发生更改,此代码可能仍然有效。

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.一个潜在的缺点是,如果您的 json 结构非常深(例如数百或数千级嵌套),您可能会在我们进行递归调用时收到 StackOverflowException。 This might or might not be likely depending on your scenario.这可能会也可能不会,具体取决于您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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