0

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']"
Community
  • 1
  • 1
Paolo
  • 20,112
  • 21
  • 72
  • 113
  • 1
    Why not access the attribute of the exception that contains the list? – Ignacio Vazquez-Abrams Oct 14 '12 at 19:39
  • I did that, but for the way xmlrpclib Fault objects work I don't think is possible (or maybe it is and I just don't know how to do it). http://docs.python.org/library/xmlrpclib.html#fault-objects. – Paolo Oct 14 '12 at 19:44

2 Answers2

4

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']
root
  • 76,608
  • 25
  • 108
  • 120
1

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • In my case `exc.args` is an empty tuple. – Paolo Oct 14 '12 at 19:49
  • @Guandalino: The exception could be ignoring conventions. Do a `print dir(exc)` to detect what attributes it *does* have, or show us the real exception rather than a example module name. – Martijn Pieters Oct 14 '12 at 19:50