I need to check that a string is valid JSON in Groovy. My first thought was just to send it through new JsonSlurper().parseText(myString)
and, if there was no exce
can validate like this:
assert JsonOutput.toJson(new JsonSlurper().parseText(myString)).replaceAll("\\s", "") ==
myString.replaceAll("\\s", "")
or a bit cleaner:
String.metaClass.isJson << { ->
def normalize = { it.replaceAll("\\s", "") }
try {
normalize(delegate) == normalize(JsonOutput.toJson(new JsonSlurper().parseText(delegate)))
} catch (e) {
false
}
}
assert '{"key":"value"}'.isJson()
assert !''.isJson()