python ast vs json用于str到dict翻译 [英] python ast vs json for str to dict translation

查看:26
本文介绍了python ast vs json用于str到dict翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码接收格式化为python字典的字符串

I have a piece of code that receives a string formatted as a python dictionary

"{'a':'1','b':'2',...}"

我需要将其转换为合适的字典.

which I need to convert to a proper dictionary.

我尝试了两种方法,使用 json.loads(s)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 表达式的字符串.提供的字符串或节点只能包含遵循 Python 文字结构:字符串、数字、元组、列表、字典、布尔值和无.

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

这可用于安全地评估包含来自不受信任来源的 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翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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