3

我有以下 JSON 作为输出:-

def desiredJson = '{"count": 4, "max": "12", "min": 0, "details": [{"goBus": {"first": 12800, "second": 11900, "third": 12800},"goAir": {"first": 12800, "second": 11900, "third": 12800}, "gotTrain": {"first": 12800, "second": 11900},"sell": true, "darn": 2,"rate": [{ "busRate": 11900, "flag": false, "percent": 0}],}],}'

我想删除“计数”键及其值,删除

"goBus": {
    "first": 12800,
    "second": 11900,
    "third": 12800
},

并删除“详细信息”节点的方括号。

我试过下面的代码来删除和替换为空: -

def slurper = new JsonSlurper();
def json = slurper.parse(file)

def newjson = JsonOutput.toJson(json).toString()

String j = "max"
newjson = newjson.replaceAll(""+ j +"", "")

log.info newjson

作为输出,最大值不会被删除。或者有没有其他方法可以从 JSON 中删除这些所有东西。

有人可以帮我吗?

我也试过这个: -

def json = new JsonSlurper().parseText(desiredJson)
def njson =  json.details.goBus

def pjson = njson.remove()

log.info JsonOutput.toJson(pjson)

它返回错误。

4

2 回答 2

3

字符串替换通常没有理由这样做——它有很大的潜力把事情搞砸。您可以在将映射写回 JSON 之前对其进行修改。例如:

import groovy.json.*

def jsonStr = '{"a": 1, "b": [{"c": 3, "d": 4}]}}'
def json = new JsonSlurper().parseText(jsonStr)
// XXX: first "de-array" `b`
json.b = json.b.first()
// next remove `c` from it
json.b.remove('c')
println JsonOutput.toJson(json)
// => {"a":1,"b":{"d":4}}

编辑:

OP 还希望摆脱数组,尽管这会混淆命名,并且仅在至少有一个元素时才有效(见评论)

于 2018-01-05T10:38:43.987 回答
2

这是具有所需输出的工作解决方案

工作代码在这里工作示例

import groovy.json.* 
def jsonStr = '''{
"count": 4,
"max": "12",
"min": 0,
"details": [{
    "goBus": {
        "first": 12800,
        "second": 11900,
        "third": 12800
    },
    "goAir": {
        "first": 12800,
        "second": 11900,
        "third": 12800
    },
    "gotTrain": {
        "first": 12800,
        "second": 11900,
        "third": 12800,
        "fourth": 13000
    },
    "sell": true,
    "darn": 2,
    "rate": [{
        "busRate": 11900,
        "flag": false,
        "percent": 0
        }]
    }]
}'''

def json = new JsonSlurper().parseText(jsonStr) 
json.details[0].remove('goBus') 
println JsonOutput.toJson(json) ​
于 2018-01-05T12:27:24.020 回答