Reputation: 2385
I am trying to create son object out of the raw string that I receive in real time stream for processing. String I am processing is:
{‘check_1’:{‘key_1’:15017.118,‘key_2’:’HTTPConnectionPool(host=‘host_1’, port=80): Read timed out. (read timeout=15)’,’key_3’:’Some reason here’}}
I am trying to replace the single quote with the double quotes with something like
str = str.replace(",'", ',"').replace("',", '",')
str = str.replace(":'", ':"').replace("':", '":')
str = str.replace("{'", '{"').replace("'}", '"}')
but value for key_2
is causing the problem when I do json.loads(str)
because value of key_2
has multiple single quotes.
One way I am thinking is using regex with back propagation. Is there is any other way to convert this type of strings into son object.
Upvotes: 1
Views: 633
Reputation: 56
This quick hack with re library seems to work
import re
thestring = re.sub(r'[‘’]', '"', thestring) # don't call your variable str
thestring = re.sub(r'="(\S+)"', r"='\1'", thestring)
print( json.loads(thestring))
Upvotes: 1