0
votes

I posted this question in the Groovy mailing lists, but I've not yet gotten an answer. I was wondering if someone can help here. I am re-posting relevant text from my original question.

I have an input json that’s nested, that is read via a JsonSlurper, and some of the keys have hyphens in them. I need to replace those keys that have hyphens with underscores and convert it back to json for downstream processing. I looked at the JsonGenerator.Options documentation and I could not find any documentation for this specific requirement.

I also looked through options to iterate through the Map that is produced from JsonSlurper, but unfortunately I’m not able to find an effective solution that iterates through a nested Map, changes the keys and produces another Map which could be converted to a Json string.

Example Code

import groovy.json.*

// This json can be nested many levels deep
def inputJson = """{
    "database-servers": {
        "dc-1": [
            "server1",
            "server2"
        ]
    },
    "discovery-servers": {
        "dc-3": [
            "discovery-server1",
            "discovery-server2"
        ]
    }
}
"""

I need to convert the above to json that looks like the example below. I can iterate through and convert using the collectEntries method which only works on the first level, but I need to do it recursively, since the input json can be an nested many levels deep.


{
    "database_servers": {
        "dc_1": [
            "server1",
            "server2"
        ]
    },
    "discovery_servers": {
        "dc_3": [
            "discovery-server1",
            "discovery-server2"
        ]
    }
}
1
please edit your question and add the groovy code, json sample, and expected result - daggett
Done. Please let me know if this is appropriate. Thank you! - Ramesh Venkitaswaran
you just need to create own recursive function - daggett

1 Answers

0
votes

Seems like you just need a recursive method to process the slurped Map and its sub-Maps.

import groovy.json.JsonSlurper

JsonSlurper slurper = new JsonSlurper()
def jsonmap = slurper.parseText( inputJson )

Map recurseMap( def inputMap ) {
    return inputMap.collectEntries { key, val ->
        String newkey = key.replace( "-", "_" )
        if ( val instanceof Map ) {
            return [ newkey, recurseMap( val ) ]
        }
        return [ newkey, val ]
    }
}

def retmap = recurseMap( jsonmap )
println retmap // at this point you can use output this however you like