我有一个这样的json形式的字符串
{"1":"abc"abc"abc","2":"xyz"xyz"xyz"}
但是,如果我想将其转换为json数据,则需要删除“”之间的“”,并得到如下所示的字符串
{"1":"abcabcabc","2":"xyzxyzxyz"}
我尝试使用re.sub来执行此操作,但是失败了。有人可以帮我吗? 我的脚本如下:
a='{"1":"abc"de"fg","2":"xyz"xyz"xyz"}'
r = re.compile(r'(?<!\:)(?<=.+)"|(?<!,)"|"(?!}|,)')
b = r.sub('', a)
print(b)
运行脚本时,结果如下:
Traceback (most recent call last):
File "./_t1.py", line 5, in <module>
r = re.compile(r'(?<!\:)(?<=.+)"|(?<!,)"|"(?!}|,)')
File "/home/emc/ssd/anaconda3/lib/python3.6/re.py", line 233, in compile
return _compile(pattern, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 566, in compile
code = _code(p, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 551, in _code
_compile(code, p.data, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 187, in _compile
_compile(code, av, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 160, in _compile
raise error("look-behind requires fixed-width pattern")
sre_constants.error: look-behind requires fixed-width pattern
答案 0 :(得分:6)
如果您的数据不包含,
或:
,则可以使用此方法,因为我们需要一些锚点来解开这种混乱:
import re
a='{"1":"abc"de"fg","2":"xyz"xyz"xyz"}'
b = re.sub('"((?:[^,:]|")*)"',lambda m : '"{}"'.format(m.group(1).replace('"','')),a)
>>> b
'{"1":"abcdefg","2":"xyzxyzxyz"}'
(?:[^,:]|")
组,以告诉它们匹配引号或逗号和冒号以外的任何内容。现在b
可以解析为json:
>>> import json
>>> json.loads(b)
{'1': 'abcdefg', '2': 'xyzxyzxyz'}
现在如果字符串包含:
怎么办?上面的解决方案不起作用。我们必须适应它:
":"
分割(可能有空格)":"
像这样:
import re,json
# a lot of colons in keys & values
a='{"1":"a:bc"de"fg","2:":"xy::z"xyz"xyz"}'
b = '":"'.join(re.sub('((?:[^,:]|")*)"',lambda m : '{}"'.format(m.group(1).replace('"','')),x) for x in re.split('"\s*:\s*"',a))
print(json.loads(b))
正确解析json
:
{'1': 'a:bcdefg', '2:': 'xy::zxyzxyz'}