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

I am trying to replace escaped double quotes to single quotes in a key value pair

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)

With the above code, I got an output \'Coffee ?\' instead of the entire string. I would like to replace the double quote only within the value part.

String : "key":"How are you? "Great!" he said. "Coffee ?"",

Expected String : "key":"How are you? 'Great!' he said. 'Coffee ?'",

解决方案

This answer is just following the comments we've exchanged:

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)

Output

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

你可能感兴趣的:(python转义引号的用法)