问题描述
我有一个字典,它作为字符串存储在 db 字段中.我正在尝试将其解析为 dict,但是 json.loads
给了我一个错误.
为什么 json.loads
会失败而 ast.literal_eval
会起作用?一个比另一个更可取吗?
json.loads
失败,因为您的 c.iframe_data
值不是有效的 JSON 文档.在有效的 json
文档中,字符串用双引号引起来,并且没有像 u
这样的将字符串转换为 unicode 的东西.
使用json.loads(c.iframe_data)
表示反序列化c.iframe_data
JSON
文档ast.literal_eval
在您需要 eval 来评估 input
表达式时使用.如果您将 Python 表达式作为要计算的输入.
一个比另一个更可取吗?
这取决于数据.请参阅此答案了解更多背景信息.
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.
It depends on the data. See this answer for more context.
这篇关于为什么 json.loads 比 ast.literal_eval 更适合解析 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!