带有转义引号的 Groovy JsonSlurper JSON 值

Thy*_*sus 4 string groovy json escaping jsonslurper

我正在开发一个用 Groovy 编写的小工具,用于解析电子邮件中的 JSON 字符串。其中一些 JSON 字符串具有包含转义引号的 JSON 值。

例如:

{
   "hello": "world with \"quotation marks\""
}
Run Code Online (Sandbox Code Playgroud)

为了解析这些字符串,我使用了 Groovy 的 JsonSlurper。以下代码演示了我的问题:

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

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

有关实时演示,请参阅https://groovyconsole.appspot.com/script/6193189027315712

执行此代码时,抛出以下异常:

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""
............................^
Run Code Online (Sandbox Code Playgroud)

因此,JsonSlurper 会忽略引号的转义。不幸的是,我无法控制输入,即 JSON 字符串。因此,我必须找到一种方法将这样的 JSON 字符串解析为映射或任何其他适当的数据结构。

San*_*nia 6

该字符串未在 json 中正确转义。文本数据应该是这样的:

'''
{
"hello": "world with \\\"quotation marks\\\""
}
'''
Run Code Online (Sandbox Code Playgroud)

您得到的字符串表明邮件正文包含格式的 json: { "hello": "world with "quotation marks"" } 虽然它应该像 { "hello": "world with \"quotation marks\"" } 如果较早是这种情况,那么您无法解析无效的 json,因为代码无法识别转义数据。

  • 使用斜线字符串消除了转义反斜线的需要,例如:/ { "hello": "world with \"quotation orders\"" } / (2认同)