Created
August 17, 2017 13:45
-
-
Save mig82/a647272ce2bc07610a5eff6967442dd8 to your computer and use it in GitHub Desktop.
How to parse json into a serializable HashMap in Jenkins Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} |
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
}
}
What about https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace ?
You saved me, thanks!
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;
}
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
}
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
}
@marslo nice! you forgot recursion though
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this works, thanks
but it works only when the map is flat, not handling nested LazyMap