替换字符串中的单引号但不转义单引号

Replace single quotes in a string but not escaped single quotes

我正在发出 Python API 获取请求并获得 JSON 我在字符串中捕获的结果。该字符串类似于包含字典的字符串文字:{'key1': 4, 'key2': 'I\'m home'}。我需要将其格式化为包含适当 JSON 对象的字符串文字,如下所示:{"key1": 4, "key2": "I\'m home"},以便我可以保存到 JSON 文件。

为了实现这一点,我尝试使用带有 negative look-ahead 的正则表达式来替换所有单引号(转义单引号除外),如下所示:

import re

#.... other codes
str = re.sub("'(!?\')", "\"", result) # result = "{'key1': 4, 'key2': 'I\'m home'}"
print (str)

但我得到了这个输出

{"key1": 4, "key2": "I"m home"}

而不是

{"key1": 4, "key2": "I\'m home"}

如何创建正则表达式,以便保留转义的单引号 \' 并将所有其他引号替换为双引号。

你需要一个负面的回顾,而不是一个负面的前瞻(“引号前没有反斜杠”):

result = '''{'key1': 4, 'key2': 'I\'m home'}'''
print(re.sub(r"(?<!\)'", '"', result))
#{"key1": 4, "key2": "I\'m home"}