代码之家  ›  专栏  ›  技术社区  ›  Kai Wang

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

  •  2
  • Kai Wang  · 技术社区  · 8 年前

    我在json字符串中得到了一个意外的引号,使之成为json。加载(jstr)失败。

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

    所以我想使用正则表达式来匹配和删除“content”值中的引号。我试过了 other solution :

    import re
    json_str = '''{"id":"9","ctime":"2018-02-13","content":"abcd: "efg.","hots":"103b","date_sms":"2017-11-22"}'''
    pa = re.compile(r'(:\s+"[^"]*)"(?=[^"]*",)')
    pa.findall(json_str)
    
    [out]: []
    

    有没有办法修理绳子?

    2 回复  |  直到 8 年前
        1
  •  3
  •   Jan    8 年前

    正如@jornsharpe所指出的,您最好清理源代码。
    也就是说,如果您无法控制额外报价的来源,您可以使用 (*SKIP)(*FAIL) 使用较新的 regex 模块和neg。像这样的周围环境:

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

    看见 a demo on regex101.com .


    在里面 Python :
    import json, regex as re
    
    json_str = '''{"id":"9","ctime":"2018-02-13","content":"abcd: "efg.","hots":"103b","date_sms":"2017-11-22"}'''
    
    # clean the json
    rx = re.compile('''"[^"]+":\s*"[^"]+"[,}]\s*(*SKIP)(*FAIL)|(?<![,:])"(?![:,]\s*["}])''')
    json_str = rx.sub('', json_str)
    
    # load it
    
    json = json.loads(json_str)
    print(json['id'])
    # 9
    
        2
  •  0
  •   Kai Wang    8 年前

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

    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)