我们的代码中存在一个错误,我们不小心从 JSON 中删除了所有转义字符,导致记录无效。我们的原始版本看起来像这样,其中
metadata
字段包含一个字符串化的 JSON 对象。
{
"id": "123ab",
"operation": "foo",
"metadata": "{\"source\": \"ddb\", \"destination\": \"s3\"}",
"data": "02-02-2024"
}
解析后,
metadata
字段无效。
{
"id": "123ab",
"operation": "foo",
"metadata": "{"source": "ddb", "destination": "s3"}",
"data": "02-02-2024"
}
有没有办法获取这个无效的 JSON 并手动修复元数据字段?不幸的是,从源头修复它并不是一个选择。
我还没有进行广泛的极端情况测试,但我认为这可以满足您的需要。基本上,如果我们在双引号字符串内看到左大括号,那么我们就会开始转义任何引号,直到看到右大括号。
这可能会被病态输入所愚弄,但我不确定是否存在一般情况的答案。
import json
s = '{"id": "123ab","operation": "foo","metadata": "{"source": "ddb", "destination": "s3"}","data": "02-02-2024"}'
# So, if we get a curly brace inside a quote, all quote marks need to be escaped
# until we see the matching close brace.
out = ''
brace = 0
quote = 0
for c in s:
if c == '{' and quote:
brace += 1
if c == '"':
if brace:
out += '\\'
quote = 1 - quote
if c == '}' and quote:
brace -= 1
out += c
print(out)
输出:
timr@Tims-NUC:~/src$ python x.py | jq
{
"id": "123ab",
"operation": "foo",
"metadata": "{\"source\": \"ddb\", \"destination\": \"s3\"}",
"data": "02-02-2024"
}