首页 > 解决方案 > 使用正则表达式将转义的双引号替换为 Python 中的单引号

问题描述

我正在尝试将键值对中的转义双引号替换为单引号

import re
import json
js = r'{"result":"{\"key\":\"How are you? \"Great!\" he said. \"Coffee ?\"\"},{\"key\":\" 2. \"Why not sure\". They walked away\"}"}'
#print(js)
data1 = json.loads(js)
s = data1['result']
#print(s)
# {"key":"How are you? "Great!" he said. "Coffee ?""},{"key":" 2. "Why not, sure.". They walked away"}
p = re.compile(r"\"key\":\"(.*\"(.*)\".*)\"")
print(p.sub(r'\'\2\'',s))
# {\'Why not, sure.\'}
json_string = "[{0}]".format(p.sub(r'\'\1\'',s))
data_list = json.loads(json_string)

使用上面的代码,我得到了一个输出 \'Coffee ?\' 而不是整个字符串。我想只在值部分替换双引号。

String : "key":"你好吗?"太好了!"他说。"咖啡?"",

预期字符串: “key”:“你好吗?'太好了!' 他说。'咖啡?'",

标签: pythonjsonregex

解决方案


这个答案只是在我们交换的评论之后:

import json
js = r'{"result":"{\"key\":\"How are you? \"Great!\" he said. \"Coffee ?\"\"},{\"key\":\" 2. \"Why not sure\". They walked away\"}"}'
data1 = json.loads(js)
s = data1['result']

good_characters = [":","{","}", ","]
result = "" 
for key, value in enumerate(s):
    if (value == "\"" and s[key-1] not in good_characters) and (value == "\"" and s[key+1] not in good_characters):
        result += '\''  
    else:
        result += value

print (result)

输出

{"key":"How are you? 'Great!' he said. 'Coffee ?'"},{"key":" 2. 'Why not sure'. They walked away"}

推荐阅读