Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse python b' string containing dict

Tags:

python

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.

like image 689
Sony George Avatar asked Sep 11 '15 12:09

Sony George


People also ask

How do you parse a dictionary from a string in Python?

eval() is an inbuilt python library function used to convert string to dictionary efficiently. For this approach, you have to import the ast package from the python library and then use it with the literal_eval() method.

How do you get a specific value from a dict?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

What will be return by dict items () *?

Python Dictionary items() Method The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.


1 Answers

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']
like image 104
Daniel Roseman Avatar answered Oct 16 '22 04:10

Daniel Roseman