使用正则表达式替换json中的额外引号

2024-10-04 05:34:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在json字符串中意外地引用了一个json.loads(jstr)失败。在

json_str = '''{"id":"9","ctime":"2018-02-13","content":"abcd: "efg.","hots":"103b","date_sms":"2017-11-22"}'''

所以我想使用正则表达式来匹配和删除“content”值内的引号。我在other solution中尝试了一些东西:

^{pr2}$

有办法把绳子修好吗?在


Tags: 字符串idjsondatecontentsms引号other
2条回答

我使用了一种可能的解决方案:

whole = []
count = 0
with open(filename) as fin:
    for eachline in fin:
        pa = re.compile(r'"content":\s?"(.*?","\w)')
        for s in pa.findall(eachline):
            s = s[:-4]
            s_fix = s.replace("\"","")
            eachline = eachline.replace(s,s_fix)

        data = json.loads(eachline)
        whole.append(data)

正如@jornsharpe所说,你最好还是清理一下源头。
也就是说,如果您不能控制额外的引号来自何处,您可以使用(*SKIP)(*FAIL),使用新的regex模块和neg。像这样看:

"[^"]+":\s*"[^"]+"[,}]\s*(*SKIP)(*FAIL)|(?<![,:])"(?![:,]\s*["}])

a demo on regex101.com


Python中: ^{pr2}$

相关问题 更多 >