0

How do parse this json in jenkins pipeline. I tried several options link org.groovy.StringEscapeUtils , JsonSlurper.

Nothing seems to work , Need help on the same

import groovy.json.JsonException
import groovy.json.JsonSlurper


try {      
  print new JsonSlurper().parseText('''
    {
      \"hello\": \"world with quotation marks\"
    }
  ''')
} catch (JsonException | IllegalArgumentException e) {
  print e
}
​

output : [hello:world with quotation marks]

Expected : {"hello" : "world with quotation marks"}

2 Answers2

0

I used an external tool Jq to overcome this challenge.

0

I don't know if you managed this. But here is some working code that I am using this :

import groovy.json.JsonBuilder
import groovy.json.StringEscapeUtils

def someMethod() {
    def randomGroovyMap = [toto: "éééèèè", titi: "heyyy"]
    echo "Result = ${mapAsStringJson(randomGroovyMap, false)}"
}

def mapAsStringJson(Map theMap = [:], boolean pretty = true) {
    try {
        def theJson = new JsonBuilder(theMap)
        def jsonMapString = pretty ? theJson.toPrettyString() : theJson.toString()
        return StringEscapeUtils.unescapeJavaScript(jsonMapString)
    } catch (error) {
        echo "Could not transform map to JSON, returning original map. Error : $error")
        return theMap
    }
}

output:

{"toto": "éééèèè","titi": "heyyy"}

Bonus : without the false, you can print a pretty output:

{
    "toto": "éééèèè",
    "titi": "heyyy"
}
Deunz
  • 1,776
  • 19
  • 32