ast.literal_eval ValueError('格式错误的字符串')

时间:2016-04-18 16:25:44

标签: python

我有一个{"Top":[{"A":1,"B":721.0,"C":false}]}形式的字符串,我希望将其转换为Python集合。

我尝试使用ast.literal_eval这样:

x = '{"Top":[{"A":1,"B":721.0,"C":false}]}'
print ast.literal_eval(x)

但是,我收到此错误:

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

如何将该字符串转换为集合?

1 个答案:

答案 0 :(得分:5)

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

>>> ast.literal_eval('False')
False

但您可能希望使用json.loads,因为您的字符串看起来像有效的json(并且json.loadsast.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}]}