mnowotka
mnowotka

Reputation: 17218

python list from string

problem is self explanatory:

import simplejson as json
a = u"[(datetime.datetime(2012, 3, 13, 14, 50, 13, 996833), 'ACTIVE', [u'my.test.service', '{}'])]"
json.loads(a)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 384, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 1 (char 1)

Question is obvious: How can I convert my string to a list?

Upvotes: 0

Views: 473

Answers (3)

Jerome Martin
Jerome Martin

Reputation: 36

You can't. (datetime.datetime(2012, 3, 13, 14, 50, 13, 996833) has no meaning in JSON. Conversely, if you try to do the opposite, you'll notice the problem:

json.dumps([(datetime.datetime(2012, 3, 13, 14, 50, 13, 996833), 'ACTIVE' [u'my.test.service', '{}'])])

TypeError: datetime.datetime(2012, 3, 13, 14, 50, 13, 996833) is not JSON serializable

Edit:

Actually, reading your question again made me notice you did not specify you wanted to use JSON, just "convert the string to a list". Not sure what your use case is, but this will work in your case:

In [23]: a = "[(datetime.datetime(2012, 3, 13, 14, 50, 13, 996833), 'ACTIVE', [u'my.test.service', '{}'])]"
In [24]: eval(a)
Out[24]: [(datetime.datetime(2012, 3, 13, 14, 50, 13, 996833), 'ACTIVE', [u'my.test.service', '{}'])]

Upvotes: 2

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

You can't use a function inside of your code. You need to break the datetime() out of your JSON stream, or put it into the right format. Try parsing known JSON code first.

Upvotes: 0

user1173922
user1173922

Reputation: 111

The first character when you're assigning a is a 'u' but with no quotes. Try removing that and see how it goes, like this:

import simplejson as json
a = "[(datetime.datetime(2012, 3, 13, 14, 50, 13, 996833), 'ACTIVE', [u'my.test.service', '{}'])]"
json.loads(a)

Upvotes: -1

Related Questions