Home > database >  Python Byte to List
Python Byte to List

Time:07-19

I am using redis.get method and it's returns me byte.

In redis ı have a list like that:

[
    "ADA/USD",
    "ADA/USDT",
    "ALGO/USD",
    "ATOM/USD"
]

When get this list inside of my script with redis.get

It's return me

b'["ADA/USD","ADA/USDT","ALGO/USD","ATOM/USD"]'

How can I convert to a "Byte" to "List" ?

CodePudding user response:

import json

json.loads(b'["ADA/USD","ADA/USDT","ALGO/USD","ATOM/USD"]'.decode())

CodePudding user response:

If you want to convert the bytes to a list - you could convert it to a string object and then split (after replacement) -

x = b'["ADA/USD","ADA/USDT","ALGO/USD","ATOM/USD"]'.decode().replace('[', '').replace(']', '').split(',')

Output

# print(x)
['"ADA/USD"', '"ADA/USDT"', '"ALGO/USD"', '"ATOM/USD"']
# print(type(x))
<class 'list'>

CodePudding user response:

x = b'["ADA/USD","ADA/USDT","ALGO/USD","ATOM/USD"]'
my_list = eval(x)
print(my_list) # ['ADA/USD', 'ADA/USDT', 'ALGO/USD', 'ATOM/USD']
print(type(my_list)) # <class 'list'>

Note: this could be dangerous if you're accepting a user input and then evaluating: check first that x is not something like __import__('shutil').rmtree('/')

  • Related