【问题标题】:Regular expression to fix double quotes in malformed "JSON" data正则表达式修复格式错误的“JSON”数据中的双引号
【发布时间】:2021-10-08 18:08:35
【问题描述】:

我使用的是 Python 3.7。我需要一个正则表达式来查找双引号内“坏值”的开始和停止位置。我的 JSON 看起来与以下内容几乎相同。

[
 {
  "key": "test1",
  "value": "<a href="http://something.com">something.com</a>",
 },
 {
  "key": "test2",
  "value": [
   "i have some "double" quotes",
   "<div class="test">some html may exists as well</div>"
  ]
 }, 
 // repeats arbitrary number of times
]

如您所见,问题存在(据我所知)只有value 键的值。此外,value 键的值可以是字符串或字符串数​​组。如果我在值中转义双引号,我可以使用 Python 的 json 模块将数据/字符串加载为字典,这是我的目标。

感谢任何有关使用正则表达式或任何其他解决方案来跟踪开始和停止双引号,然后转义其中的双引号的提示。

例如,我想要一个正则表达式来查找以下值

  • "&lt;a href="http://something.com"&gt;something.com&lt;/a&gt;"
  • "i have some "double" quotes"
  • "&lt;div class="test"&gt;some html may exists as well&lt;/div&gt;"

并将它们替换如下

  • "&lt;a href=\"http://something.com\"&gt;something.com&lt;/a&gt;"
  • "i have some \"double\" quotes"
  • "&lt;div class=\"test\"&gt;some html may exists as well&lt;/div&gt;"

【问题讨论】:

  • 我认为 JSON 解析可以使用 PDA 完成,其中正则表达式与 FSA 兼容。因此,你不能,或者至少你不应该……
  • @KemalKaplan PDA 和 FSA 是什么?
  • 它们是下推自动机与有限状态自动机。有一个不错的 wiki 页面。 en.wikipedia.org/wiki/Chomsky_hierarchy

标签: python json regex escaping


【解决方案1】:

这是一种特别适用于您的示例的方法:

对于这段代码,我将 JSON 存储在 c:\temp\input.json

import re

f = open(r'c:\temp\input.json', 'r')
lines = f.read()
f.close()

def replace(m):
    return '"' + m.group(1).replace('\"', '\\\"') + '"'

# escape all nested quote characters
lines = '\n'.join([re.sub('\"(.*)\"', replace, line) for line in lines.split('\n')])
        
# the code does some unwanted replacements, like this:
# "key": "test1", ---> "key\": \"test1",
# the next line reverts that
lines = lines.replace('\\\": \\\"', '\": \"')

print(lines)

这并不令人惊奇,需要处理更复杂的输入,但希望这很有用。

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 2011-09-15
    • 1970-01-01
    • 2021-11-14
    • 2017-04-05
    • 1970-01-01
    • 2015-12-24
    • 2021-08-03
    • 2016-02-14
    相关资源
    最近更新 更多