Reputation: 765
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 ?'",
Upvotes: 0
Views: 366
Reputation: 8589
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"}
Upvotes: 2
Reputation: 1
If the key is consistent across the string then this would work
s = data1['result']
','.join([d[:8] + d[8:-2].replace('"',"'") + d[-2:] for d in s.split(',')])
Upvotes: 0