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;
}
@tfront
Copy link

tfront commented Mar 21, 2019

this works, thanks
but it works only when the map is flat, not handling nested LazyMap

@diroussel
Copy link

diroussel commented Jun 12, 2019

This is a way to do it recursively:

  @NonCPS
  @CompileStatic
  static def convertLazyMapToLinkedHashMap(def value) {
    if (value instanceof LazyMap) {
      Map copy = [:]
      for (pair in (value as LazyMap)) {
        copy[pair.key] = convertLazyMapToLinkedHashMap(pair.value)
      }
      copy
    } else {
      value
    }
  }

@amaslak0v
Copy link

@a-langer
Copy link

Based on @diroussel code, I made an improved version:

@NonCPS
def toToLinkedHashMap(def obj) {
    if (obj instanceof groovy.json.internal.LazyValueMap) {
        Map copy = [:];
        for (pair in (obj as Map)) {
            copy.put(pair.key, toToLinkedHashMap(pair.value));
        }
        return copy;
    }
    if (obj instanceof groovy.json.internal.ValueList) {
        List copy = [];
        for (item in (obj as List)) {
            copy.add(toToLinkedHashMap(item));
        }
        return copy;
    }
    return obj;
}

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