-
慕田峪9158850
Groovy 已经提供了类和机制来做到这一点,首先你需要导入类groovy.json.JsonGenerator然后您可以定义要从序列化中忽略的字段:def generator = new JsonGenerator.Options() .excludeFieldsByName('id', 'Code') .build()最后只需要解析输出:String output = generator.toJson(input)输出将如下所示:{ "Status": "Fail", "Rules": [ { "Status": "Fail", "Message": "Code error" }, { "Status": "Fail", "Message": "Configuration error" } ]}这是我如何做到这一点的完整示例:import groovy.json.JsonSlurperimport groovy.json.JsonOutputimport groovy.json.JsonGeneratorString 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)
-
Qyouu
递归遍历 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 }}打印:─➤ groovy solution.groovy 1 ↵{ "Status": "Fail", "Rules": [ { "Status": "Fail", "Message": "Code error" }, { "Status": "Fail", "Message": "Configuration error" } ]}运行时。这样做的好处是它不会硬编码到您的 json 结构中,即如果结构由于某种原因发生变化,此代码可能仍然有效。一个潜在的缺点是,如果您的 json 结构非常深(例如数百或数千级嵌套),那么当我们进行递归调用时,您可能会收到 StackOverflowException。根据您的情况,这可能会也可能不会。
-
暮色呼如
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);注意:-您可以简单地使用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)