I have a dictionary that is stored in a db field as a string. I am trying to parse it into a dict, but json.loads
gives me an error.
Why does json.loads
fail on this and ast.literal_eval
works? Is one preferable over the other?
>>> c.iframe_data
u"{u'person': u'Annabelle!', u'csrfmiddlewaretoken': u'wTE9RZGvjCh9RCL00pLloxOYZItQ98JN'}"
# json fails
>>> json.loads(c.iframe_data)
Traceback (most recent call last):
ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
# ast.literal_eval works
>>> ast.literal_eval(c.iframe_data)
{u'person': u'Annabelle!', u'csrfmiddlewaretoken': u'wTE9RZGvjCh9RCL00pLloxOYZItQ98JN'}
json.loads
failed because your c.iframe_data
value is not a valid JSON document. In valid json
document string are quoted in double quote and there isn't anything like u
for converting strings to unicode.
Using json.loads(c.iframe_data)
means deserialize the JSON
document in c.iframe_data
ast.literal_eval
is used whenever you need eval to evaluate input
expression. If you have Python expressions as an input that you want to evaluate.
Is one preferable over the other?
It depends on the data. See this answer for more context.