简体   繁体   English

字符串中的python列表

[英]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? 问题很明显:如何将字符串转换为列表?

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: (datetime.datetime(2012,3,13,14,50,13,996833)在JSON中没有意义。相反,如果尝试相反的操作,则会发现问题:

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". 实际上,再次阅读您的问题使我注意到您没有指定要使用JSON,只是“将字符串转换为列表”。 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', '{}'])]

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. 您需要将datetime()从JSON流中分离出来,或将其放入正确的格式中。 Try parsing known JSON code first. 尝试先解析已知的JSON代码。

The first character when you're assigning a is a 'u' but with no quotes. 分配a时的第一个字符是'u',但不带引号。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM