json - 带有转义引号的 Groovy JsonSlurper JSON 值

标签 json string groovy escaping jsonslurper

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

例如:

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

为了解析这些字符串,我使用 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
}

参见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""
............................^

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

最佳答案

字符串在 json 中未正确转义。文本数据应类似于:

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

您收到的字符串表明邮件正文包含以下格式的 json: { "hello": "带有“引号”的世界" } 虽然它应该像 { "hello": "带有\"引号\"的世界" } 如果是较早的情况,那么您无法解析无效的 json,因为代码无法识别转义的数据。

关于json - 带有转义引号的 Groovy JsonSlurper JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34808352/

相关文章:

javascript - 使用 JSON.parse 重命名 JSON 字段

c# - 如何使用c#将字符串与另一个字符串进行比较

JavaScript 正则表达式模式

map - 如何在不覆盖当前条目的情况下添加多个 Groovy 映射条目?

grails - @Selector并通知

java - Groovy 语言有 ?.处理NullPointer异常的语法,scala中有类似的东西吗?

javascript - Newtonsoft.JsonConvert - 如何将 JavaScript 对象反序列化为一个属性为 Enum 的对象?

php - json_decode() 无法正常工作

java - 字符串比较时获取空指针异常

json - React JSON 架构依赖关系