为什么解析JSON应该优先使用ast.literal_eval和json.loads? [英] Why should json.loads be preferred to ast.literal_eval for parsing JSON?

查看:530
本文介绍了为什么解析JSON应该优先使用ast.literal_eval和json.loads?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,该字典以字符串形式存储在db字段中.我正在尝试将其解析为字典,但是json.loads给了我一个错误.

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.

为什么json.loads对此失败并且ast.literal_eval起作用?一个比另一个好吗?

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失败,因为您的c.iframe_data值不是有效的

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.

使用 json.loads(c.iframe_data) 意味着反序列化 c.iframe_data

ast.literal_eval在需要评估e input表达式时使用.如果您有Python表达式作为您要评估的输入.

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?

这取决于数据.有关更多背景信息,请参见 answer .

It depends on the data. See this answer for more context.

这篇关于为什么解析JSON应该优先使用ast.literal_eval和json.loads?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆