Search code examples
jsonstringgroovyescapingjsonslurper

Groovy JsonSlurper JSON value with escaped quotation marks


I'm developing a small tool written in Groovy which parses JSON strings in emails. Some of these JSON strings have JSON values that contain escaped quotes.

For example:

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

To parse these strings, I am using Groovy's JsonSlurper. The following code demonstrates my problem:

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

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

See https://groovyconsole.appspot.com/script/6193189027315712 for a live demo.

When executing this code, the following exception is thrown:

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

The current character read is 'q' with an int value of 113
expecting '}' or ',' but got current char 'q' with an int value of 113
line number 3
index number 35
      "hello": "world with "quotation marks""
............................^

Thus, the escaping of the quotation mark is ignored by JsonSlurper. Unfortunately, I have no control over the input, i.e. the JSON strings. Therefore, I have to find a way to parse such a JSON string into a map or any other appropriate data structure.


Solution

  • The string has not been escaped properly in the json. The text data should be like:

    '''
    {
    "hello": "world with \\\"quotation marks\\\""
    }
    '''
    

    The string that you are getting indicates that the mail body contains the json in format: { "hello": "world with "quotation marks"" } while it should be like { "hello": "world with \"quotation marks\"" } If earlier is the case then you can't parse the invalid json as there is no way for code to identify about the escaped data.