How to remove the JSON array, brackets, key and value using replaceAll method?

avidCoder picture avidCoder · Jan 5, 2018 · Viewed 8.5k times · Source

I have following JSON as an output:-

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}],}],}'

I want to remove "count" key and its value, remove

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

And remove square brackets of "details" node.

I have tried below code to remove and replace as null:-

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

As an output, the max value is not getting removed. Or Is there any other way we can remove these all things from JSON.

Can anybody help me on this?

I have tried this also:-

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

def pjson = njson.remove()

log.info JsonOutput.toJson(pjson)

It is returning false.

Answer

cfrick picture cfrick · Jan 5, 2018

There usually is no reason to that with string replacements -- it has just to much potential to mess something up. You can just modify the map before writing it back as JSON. E.g.:

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}}

edit:

OP also wants to get rid of the array, altough this messes with the naming and only works if there is at least one element (see comments)