>>> help(ast.literal_eval)
Help on function literal_eval in module ast:
literal_eval(node_or_string)
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.
例如:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
从Python 2.6开始,您可以使用内置的^{} :
这比使用
eval
更安全。正如它自己的文件所说:例如:
使用
json.loads
:https://docs.python.org/3.8/library/json.html
JSON可以解决这个问题,尽管它的解码器需要在键和值周围加双引号。如果你不介意替换黑客。。。
请注意,如果您的键或值中包含单引号,则这将由于字符替换不当而失败。只有当您强烈反对eval解决方案时,才建议使用此解决方案。
关于json单引号的更多信息:jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON
相关问题 更多 >
编程相关推荐