Question

Possible Duplicate:
How do I parse a string representing a nested list into an actual list?

How could I get a list of errors from this string?

>>> out = "<class 'api.exceptions.DataError'>:[u'Error 1', u'Another error']"

I tried using the json module but it didn't work.

>>> import json
>>> errors = out.split(":")[-1]
>>> my_list = json.loads(errors)

I get this exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Would you please suggest some way to adjust the code to get what I want?

Edit: added the use case.

The context where my question applies is:

try:
    # some code generating an xmlrpclib.Fault exception
    pass
except xmlrpclib.Fault, err:
    # here print dir(err) gives:
    # ['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
    # '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
    # '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
    # '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', 
    # '__unicode__', '__weakref__', 'args', 'faultCode', 'faultString', 'message']

    exit(err.faultString)
    # exits with: "<class 'api.exceptions.DataError'>:[u'Error 1', u'Another error']"
Was it helpful?

Solution

You should use:

import ast

ls="['a','b','c']"

ast.literal_eval(ls)
Out[178]: ['a', 'b', 'c']

or as a full:

In [195]: ast.literal_eval(out.split(':')[1])
Out[195]: [u'Error 1', u'Another error']

OTHER TIPS

It looks like you tried to print an exception; you can access the the arguments of the exception with the .args parameter:

print exc.args[0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top