我还没有做过广泛的角落案例测试,但我认为这正是你所需要的。基本上,如果我们在双引号字符串中看到一个大括号,那么我们就会开始转义任何引号,直到看到闭合大括号。
这可能会被病理学的输入所愚弄,但我不确定是否有一个通用的案例答案。
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"
}