Reputation: 2823
I'm making a Python API get request and getting JSON results which I have captured in a string. The string is similar to a string literal containing a dictionary: {'key1': 4, 'key2': 'I\'m home'}
. I need to format it to a string literal containing a proper JSON object like this: {"key1": 4, "key2": "I\'m home"}
, so that I can save to a JSON file.
To achieve this, I tried using regular expressions with negative look-ahead to replace all the single quotes (except the escaped single quote) like this:
import re
#.... other codes
str = re.sub("'(!?\')", "\"", result) # result = "{'key1': 4, 'key2': 'I\'m home'}"
print (str)
But I get this output
{"key1": 4, "key2": "I"m home"}
instead of
{"key1": 4, "key2": "I\'m home"}
How do I create the regular expression, so that escaped single quotes \'
are preserved and all others are replaced with double-quotes.
Upvotes: 1
Views: 484
Reputation: 57105
You need a negative lookbehind, not a negative lookahead ("no backslash before a quote"):
result = '''{'key1': 4, 'key2': 'I\\'m home'}'''
print(re.sub(r"(?<!\\)'", '"', result))
#{"key1": 4, "key2": "I\'m home"}
Upvotes: 3