我使用hget从redis获取数据。
data = ss.hget("users", "inmove");
数据类型为str。
type(data):
"{u'free_tickets': 2, u'payment_tickets': 1200, u'last': 1420560000, u'user_id': u'inmove'}"
如果我使用json.loads(数据),错误是
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject
raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)
答案 0 :(得分:3)
使用ast.literal_eval,你的字符串数据不是json,它是python dict的字符串表示。
>>> my_str = "{u'free_tickets': 2, u'payment_tickets': 1200, u'last': 1420560000, u'user_id': u'inmove'}"
>>> from ast import literal_eval
>>> my_dict = literal_eval(my_str)
>>> my_dict.keys()
[u'last', u'user_id', u'free_tickets', u'payment_tickets']