Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert dictionary to bytes

I'm trying to convert a dictionary to bytes but facing issues in converting it to a correct format.

First, I'm trying to map an dictionary with an custom schema. Schema is defined as follows -

class User:
    def __init__(self, name=None, code=None):
        self.name = name
        self.code = code

class UserSchema:
    name = fields.Str()
    code = fields.Str()

@post_load
 def create_userself, data):
    return User(**data)

My Dictionary structure is as follows-

user_dict = {'name': 'dinesh', 'code': 'dr-01'} 

I'm trying to map the dictionary to User schema with the below code

schema = UserSchema(partial=True)
user = schema.loads(user_dict).data

While doing, schema.loads expects the input to be str, bytes or bytearray. Below are the steps that I followed to convert dictionary to Bytes

import json
user_encode_data = json.dumps(user_dict).encode('utf-8')
print(user_encode_data)

Output:

b'{"name ": "dinesh", "code ": "dr-01"}

If I try to map with the schema I'm not getting the required schema object. But, if I have the output in the format given below I can able to get the correct schema object.

b'{\n  "name": "dinesh",\n  "code": "dr-01"}\n'

Any suggestions how can I convert a dictionary to Bytes?

like image 784
Dinesh Avatar asked Mar 21 '19 09:03

Dinesh


2 Answers

You can use indent option in json.dumps() to obtain \n symbols:

import json

user_dict = {'name': 'dinesh', 'code': 'dr-01'}
user_encode_data = json.dumps(user_dict, indent=2).encode('utf-8')
print(user_encode_data)

Output:

b'{\n  "name": "dinesh",\n  "code": "dr-01"\n}'
like image 80
Alderven Avatar answered Nov 07 '22 19:11

Alderven


You can use Base64 library to convert string dictionary to bytes, and although you can convert bytes result to a dictionary using json library. Try this below sample code.

import base64
import json


input_dict = {'var1' : 0, 'var2' : 'some string', 'var1' : ['listitem1','listitem2',5]}

message = str(input_dict)
ascii_message = message.encode('ascii')
output_byte = base64.b64encode(ascii_message)

msg_bytes = base64.b64decode(output_byte)
ascii_msg = msg_bytes.decode('ascii')
# Json library convert stirng dictionary to real dictionary type.
# Double quotes is standard format for json
ascii_msg = ascii_msg.replace("'", "\"")
output_dict = json.loads(ascii_msg) # convert string dictionary to dict format

# Show the input and output
print("input_dict:", input_dict, type(input_dict))
print()
print("base64:", output_byte, type(output_byte))
print()
print("output_dict:", output_dict, type(output_dict))

enter image description here

like image 2
Saeed Zahedian Abroodi Avatar answered Nov 07 '22 17:11

Saeed Zahedian Abroodi