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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With