我正在开发一个用 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/