Skip to content

Instantly share code, notes, and snippets.

@mig82
Created August 17, 2017 13:45
Show Gist options
  • Save mig82/a647272ce2bc07610a5eff6967442dd8 to your computer and use it in GitHub Desktop.
Save mig82/a647272ce2bc07610a5eff6967442dd8 to your computer and use it in GitHub Desktop.
How to parse json into a serializable HashMap in Jenkins Groovy
@NonCPS
def parseJson(txt){
def lazyMap = new groovy.json.JsonSlurper().parseText(txt)
def map = [:]
for ( prop in lazyMap ) {
map[prop.key] = prop.value
}
return map;
}
@marcellourbani
Copy link

Another small improvement (use generic Map and List rather than specific implementations):

@NonCPS
def toSerializable(def obj) {
    if (obj instanceof Map) {
        Map copy = [:]
        for (pair in (obj as Map)) {
            copy.put(pair.key, toSerializable(pair.value))
        }
        return copy
    }
    if (obj instanceof List) {
        List copy = []
        for (item in (obj as List)) {
            copy.add(toSerializable(item))
        }
        return copy
    }
    return obj
}

@marslo
Copy link

marslo commented Oct 15, 2024

def foo( String txt ){
  def object = new groovy.json.JsonSlurper().parseText(txt)
  Map.isCase( object )  ? object.collectEntries {[ it.key, it.value ]} :
  List.isCase( object ) ? object.collect { it } : object
}

@marcellourbani
Copy link

marcellourbani commented Oct 16, 2024

@marslo nice! you forgot recursion though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment