gpt4 book ai didi

python redis hget 字符串转字典

转载 作者:IT王子 更新时间:2023-10-29 06:10:02 25 4
gpt4 key购买 nike

我使用 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(data),错误是

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)

最佳答案

使用 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']

关于python redis hget 字符串转字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27795108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com