首页 > 解决方案 > 正则表达式替换 - json中的双引号

问题描述

我有 json 字符串,它是

{“test”:”this is “test” of test”,”result”:”your result is “out” in our website”}

我需要通过 regex_replace 使它成为有效的 json,正如你在上面看到的不是有效的 json。更换后的预期结果:

{“测试”:“这是测试的‘测试’”,“结果”:“您的结果在我们的网站上是‘出’”}

您的帮助将不胜感激

标签: jsonregex

解决方案


无论内容是什么,您都可以只匹配所有字符串
,只要它被正确的 JSON 结构包围。
然后在子回调函数中相应地替换双引号。

匹配伪有效 JSON 字符串的正则表达式是这样的

r'([:\[,{]\s*)"(.*?)"(?=\s*[:,\]}])'

https://regex101.com/r/KgCz1L/1

在回调中,只需用单引号替换所有双引号'

Python 示例:

>>> import re
>>>
>>> text = '''
... {"test":"this is "test" of test","result":"your result is "out" in our website"}
... '''
>>>
>>> def repl_call(m):
...     preq = m.group(1)
...     qbody = m.group(2)
...     qbody = re.sub( r'"', "'", qbody )
...     return preq + '"' + qbody + '"'
...
>>> print( re.sub( r'([:\[,{]\s*)"(.*?)"(?=\s*[:,\]}])', repl_call, text ))

{"test":"this is 'test' of test","result":"your result is 'out' in our website"}

推荐阅读