使用正则表达式将转义的双引号替换为Python中的单引号

时间:2019-09-24 13:16:19

标签: python json regex

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

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?\',而不是整个字符串。我只想在值部分内替换双引号。

字符串:“键”:“你好吗?”太好了!“他说。”咖啡吗?“,”

期望的字符串:“键”:“你好吗?他说:“咖啡吗?”,

2 个答案:

答案 0 :(得分:2)

这个答案就跟在我们交换的评论之后:

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"}

答案 1 :(得分:0)

如果键在字符串中是一致的,那么它将起作用

s = data1['result']
','.join([d[:8] + d[8:-2].replace('"',"'") + d[-2:] for d in s.split(',')])