Groovy JSON parsing with readable error messages
Groovy
import groovy.json.JsonSlurper
import groovy.json.JsonException
def parseJson(String text) {
if (text == null || text.trim().isEmpty()) {
throw new IllegalArgumentException('JSON input is empty')
}
try {
return new JsonSlurper().parseText(text)
} catch (JsonException e) {
throw new IllegalArgumentException("invalid JSON: ${e.message}", e)
}
}
println parseJson('{"a": 1}').a
try {
parseJson('{"a": }')
} catch (IllegalArgumentException e) {
println "rejected: ${e.message.readLines().first()}"
}