bsky
bsky

Reputation: 20222

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.

I tried using ast.literal_eval like this:

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?

Upvotes: 0

Views: 5770

Answers (1)

mgilson
mgilson

Reputation: 309841

false is not accepted by 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

>>> 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)...

>>> 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}]}

Upvotes: 6

Related Questions