问题描述
我有一段代码接收格式化为python字典的字符串
I have a piece of code that receives a string formatted as a python dictionary
"{'a':'1','b':'2',...}"
我需要将其转换为
我尝试了两种方法,分别使用 json.loads($)
和 ast.literal_eval(s)
ast似乎更健壮,可以接受字符串中任何形式的引号,并且可以正常使用,而json似乎对引用非常挑剔细节,并且不会仅出现在单引号格式上。我真的很想在输入方面尽可能地灵活,因此更喜欢使用 ast
,但是,我的一些同事声称这可能不是一个安全的模块,使用的功能。
I have tried two approaches, using json.loads(s)
and ast.literal_eval(s)
ast seems to be much more robust, accepting any form of quotes in the string and "just works" while json seems to be very picky about the quoting specifics and wouldn't fail on only a single form of quote format. I really would like to be as flexible as possible with the input and thus prefer to use ast
, however, some of my colleagues claim it might not be a "safe" module and function to use.
任何人都可以对ast和ast.literal_eval()的安全性提出建议,尤其是与json.loads()相比吗?
Can anyone advise on ast and ast.literal_eval() safety, especially compared to json.loads() ?
谢谢
推荐答案
使用 ast.literal_eval()
-这是设计好的做你想做的。 JSON会在语法匹配时起作用,但这不是您应该依靠的东西。
Use ast.literal_eval()
- it's designed to do what you want. JSON happens to work as the syntax matches, but that isn't something you should rely on.
关于安全性, literal_eval()
是专为安全使用来自不受信任来源的数据而设计的。实际上,的第一个单词是安全:
As to safety, literal_eval()
is specifically designed to be safe to use on data from untrusted sources. The first word of the docs, in fact, is 'Safely':
这可用于安全地评估包含来自不受信任来源的Python表达式的字符串,而无需自己解析
的值。
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
建议您不要使用它的人可能会想到 eval()
,这确实是不安全的。
Those that advised you against using it were probably thinking of eval()
, which is indeed unsafe.
这篇关于python ast vs json用于str到dict的翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!