[英]ast.literal_eval ValueError('malformed string')
I have a string of the form {"Top":[{"A":1,"B":721.0,"C":false}]}
which I would like to convert into a Python collection. 我有一个格式为
{"Top":[{"A":1,"B":721.0,"C":false}]}
我想将其转换为Python集合。
I tried using ast.literal_eval
like this: 我尝试像这样使用
ast.literal_eval
:
x = '{"Top":[{"A":1,"B":721.0,"C":false}]}'
print ast.literal_eval(x)
However, I am getting this error: 但是,我收到此错误:
File "queryFlights.py", line 19, in <module>
print ast.literal_eval(x)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 63, in _convert
in zip(node.keys, node.values))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 62, in <genexpr>
return dict((_convert(k), _convert(v)) for k, v
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 60, in _convert
return list(map(_convert, node.elts))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 63, in _convert
in zip(node.keys, node.values))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 62, in <genexpr>
return dict((_convert(k), _convert(v)) for k, v
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
How can I convert that string into a collection? 如何将该字符串转换为集合?
false
is not accepted by ast.literal_eval
. false
不被接受ast.literal_eval
。
>>> ast.literal_eval('false')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
False
is False
是
>>> ast.literal_eval('False')
False
but you probably want to use json.loads
instead since your string looks like valid json (and json.loads
is faster than ast.literal_eval
for evaluating json strings)... 但您可能想改用
json.loads
因为您的字符串看起来像是有效的json(并且json.loads
比ast.literal_eval
评估json字符串的速度更快)...
>>> import json
>>> x = '{"Top":[{"A":1,"B":721.0,"C":false}]}'
>>> json.loads(x)
{u'Top': [{u'A': 1, u'C': False, u'B': 721.0}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.