How can I convert the str
representation of a dict
, such as the following string, into a dict
?
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
I prefer not to use eval
. What else can I use?
The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.
Starting in Python 2.6 you can use the built-in
ast.literal_eval
:This is safer than using
eval
. As its own docs say:For example:
If the string can always be trusted, you could use
eval
(or useliteral_eval
as suggested; it's safe no matter what the string is.) Otherwise you need a parser. A JSON parser (such as simplejson) would work if he only ever stores content that fits with the JSON scheme.If you can't use Python 2.6, you can use a simple safeeval implmenentation like http://code.activestate.com/recipes/364469/
It piggybacks on the Python compiler so you don't have to do all the gross work yourself.
using
json.loads
:To OP's example:
We can use Yaml to deal with this kind of non-standard json in string: