Forum Discussion
JHunt
6 years agoCommunity Hero
Use JsonSlurper and JsonOutput:
import groovy.json.JsonSlurper import groovy.json.JsonOutput String response = $/ { "employee": "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}" }/$ def parsedResponse = new JsonSlurper().parseText(response)
String formattedResponse = parsedResponse
.with (JsonOutput.&toJson >> JsonOutput.&prettyPrint)
However, if that's really the response you're getting, it looks like the API has a problem, because it's sending the employee as a string instead of an object.
assert parsedResponse.'employee' instanceof String
assert parsedResponse.'employee' == '{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}
If that is really how the API works, you could do this:
import groovy.json.JsonSlurper import groovy.json.JsonOutput String response = $/ { "employee": "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}" }/$ def parsedResponse = new JsonSlurper().parseText(response) parsedResponse.'employee' = new JsonSlurper().parseText(parsedResponse.'employee') String formattedResponse = parsedResponse .with (JsonOutput.&toJson >> JsonOutput.&prettyPrint)
Related Content
- 5 years ago
- 6 years ago
- 4 years ago
Recent Discussions
- 15 years ago