简体   繁体   English

如何解析包含dict的python b'字符串

[英]How to parse python b' string containing dict

I got below stated output when I queried hgetall to redis from a python3 script. 当我从python3脚本查询hgetallredis时,我得到了以下声明的输出。

data = {
    b'category': b'0',
    b'title': b'1',
    b'display': b'1,2',
    b'type': b'1',
    b'secret': b'this_is_a_salt_key',
    b'client': b'5'}

it was of type dict . 它是dict类型。

When I tried to get "category" like 当我试图得到“类别”时

>>> data['category']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'category'

Upon reading I tried this way 读完后我就这样试了

import ast
>>> ast.literal_eval(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib/python3.4/ast.py", line 83, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: {b'category': b'0', b'title': b'1', b'display': b'1,2', b'type': b'1', b'secret': b'this_is_a_salt_key', b'client': b'5'}

also tried using json.dumps. 也试过用json.dumps。 but could not understand the real problem. 但无法理解真正的问题。

Please help me to parse the output and get the desired result. 请帮我解析输出并获得所需的结果。

This is not JSON, so there is no point trying to parse it. 这不是JSON,因此尝试解析它没有意义。 It is a dictionary, which just happens to have keys which are byte strings. 它是一个字典,恰好有字节字符串的键。 So you simply need to use byte strings to access the values: 所以你只需要使用字节字符串来访问这些值:

data[b'category']

You have to add the b in front of the key value since it is a byte string: 您必须在键值前面添加b ,因为它是一个字节字符串:

data[b'category']

If you want to turn the byte strings into normal strings you could do: 如果要将字节字符串转换为普通字符串,可以执行以下操作:

data = {b'category': b'0', b'title': b'1', b'display': b'1,2', b'type': b'1', b'secret': b'this_is_a_salt_key', b'client': b'5'}

newData = {str(key): str(value) for (key, value) in data.items()}

print newData
 data = {key.decode('utf-8'): value.decode('utf-8') for (key, value) in c.items()}
 >>> data
 {'category': '0', 'title': '1', 'display': '1,2', 'type': '1', 'secret': 'this_is_a_salt_key', 'client': '5'}
>>> data['display']
'1,2'
>>> data['display'].split(",")
['1', '2']

this was my desired output.. thanks to all. 这是我想要的输出..感谢大家。

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

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