json - 正则表达式替换 - json中的双引号
问题描述
我有 json 字符串,它是
{“test”:”this is “test” of test”,”result”:”your result is “out” in our website”}
我需要通过 regex_replace 使它成为有效的 json,正如你在上面看到的不是有效的 json。更换后的预期结果:
{“测试”:“这是测试的‘测试’”,“结果”:“您的结果在我们的网站上是‘出’”}
您的帮助将不胜感激
解决方案
无论内容是什么,您都可以只匹配所有字符串
,只要它被正确的 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"}
推荐阅读
- java - 如何为所有非空值添加双引号,也不在 Spark Java 中的标题上添加双引号
- node.js - 带有redirect()的Node JS在将标头发送到客户端后无法设置标头
- javascript - 如何在Vue中特定组件的范围内定义`setInterval`?
- javascript - 更新使用 append() 方法和 ajax 请求
- python - 如何合并两个 .dat 文件?
- cassandra - 具有一致性级别和复制因子的 Cassandra 如何处理 CAP 定理?
- python - 使用 Python msvcrt 时出现代码问题
- python - 我试图构建一个包含孟加拉语的 doc 文件,但保存的 docx 文件在 python docx 库中没有显示任何字符
- javascript - 显示函数产生的组件,在屏幕上替换之前的组件
- php - Base64转换为pdf文件:如何让它只显示pdf的第一页?可能吗?