How to parse python b' string containing dict

2020-07-18 06:51发布

I got below stated output when I queried hgetall to redis from a python3 script.

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.

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. but could not understand the real problem.

Please help me to parse the output and get the desired result.

标签: python
3条回答
▲ chillily
2楼-- · 2020-07-18 07:26
 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.

查看更多
▲ chillily
3楼-- · 2020-07-18 07:48

This is not JSON, so there is no point trying to parse it. 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']
查看更多
孤傲高冷的网名
4楼-- · 2020-07-18 07:49

You have to add the b in front of the key value since it is a byte string:

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
查看更多
登录 后发表回答