groovyjsonslurper

How to handle raw JSON strings in JsonSlurper?


I'm currently trying to automate running Postman collections in our CI/CD tool. What I noticed is that, in general, JSON strings that also contain a raw JSON string cannot be parsed.

Here's a simple example to demonstrate this.

import groovy.json.JsonSlurper

def data = '''
{
    "request":{
        "raw": "{\n   \"Hello\": \"World\"\n}"
    }
}
'''
def parser = new JsonSlurper()
jsonData = parser.parseText(data)
println(jsonData)

I get the following error:

Caught: groovy.json.JsonException: expecting '}' or ',' but got current char ''' with an int value of 39

The current character read is ''' with an int value of 39
expecting '}' or ',' but got current char ''' with an int value of 39
line number 3
index number 7
    'request':{
....^
groovy.json.JsonException: expecting '}' or ',' but got current char ''' with an int value of 39

The current character read is ''' with an int value of 39
expecting '}' or ',' but got current char ''' with an int value of 39
line number 3
index number 7
    'request':{
....^
at main.run(main.groovy:12)

How can I get JSONSlurper to treat the value of raw as a string?


Solution

  • The way you are escaping the quotes is not correct. Please see the following.

    import groovy.json.*
    
    def data = '''
    {
        "request":{
            "raw": "\n { \\"Hello\\": \\"World\\"} \n"
        }
    }
    '''
    def parser = new JsonSlurper()
    jsonData = parser.parseText(data)
    println(jsonData)