如何使用replaceAll方法删除JSON数组、括号、键和值?
我将以下JSON作为输出:-如何使用replaceAll方法删除JSON数组、括号、键和值?,json,rest,groovy,removeall,ready-api,Json,Rest,Groovy,Removeall,Ready Api,我将以下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},"s
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}],}],}'
我想删除“count”键及其值remove
"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)
它返回false。字符串替换通常没有理由这样做——它有太多的可能把事情搞砸。您可以在将映射写回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还希望去掉数组,尽管这会弄乱命名,并且只有在至少有一个元素(请参见注释)时才起作用。这是具有所需输出的工作解决方案 这里的工作代码
这很好。但在我的例子中,我想删除“goBus”:{“first”:12800,“second”:11900,“third”:12800},它位于“details”数组节点内。。我应该如何处理这个问题?@Rao-它正在使用cfrick代码。。但是戈布斯物体并没有用同样的方法被移除。我错过了讨论中的阵列。您必须使用显式扩展运算符对每个元素执行操作。谢谢,我已经解决了它。。我已经询问过如何从desiredJson中删除“rate”数组的方括号。。否则,删除“b”数组的方括号就足够了。我们可以删除它吗?这只有在只有一个听起来不像(复数)的
细节的情况下才有意义。所以你可以用“永远第一”这样的规则。e、 g.json.details=json.details.first()
预期的输出是什么?在预期的输出中,我只得到了这个“Key”=“max”,并且没有加引号。。像这样:-'':“12”。。但是@cfrick给出的解决方案是正确的。。但它并不是用同样的方法删除这些“goBus”:{“first”:12800,“second”:11900,“third”:12800}。如果你能准确地输入所需的json而不是解释,这会有所帮助。我已经在@raoNo添加了它,我只想从desiredJson中删除这个goBus对象@尼廷那太完美了@尼廷,不管怎样,我可以让它充满活力。。比如说,如果你有戈布斯有时在其他位置。。在这种情况下,您的建议是什么。在这里,如果“详细信息”中没有嵌套对象(要删除),那么第0个位置就可以了,如果可能的话,请保持json结构的一致性。
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)