How can I convert the str
representation of a dict
, such as the following string, into a dict
?
s = \"{\'muffin\' : \'l
https://docs.python.org/3.8/library/json.html
JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...
import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}
NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.
More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON