我正在尝试将转义的双引号替换为键值对中的单引号
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”:“你好吗?'太棒了!' 他说。'咖啡?'”,
这个答案只是在我们交换的评论之后:
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"}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句