简体   繁体   English

Python:将字典转换为字节

[英]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.这样做时, schema.loads期望输入是 str、bytes 或 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?任何建议如何将字典转换为字节?

You can use indent option in json.dumps() to obtain \\n symbols:您可以在json.dumps()使用indent选项来获取\\n符号:

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}'

You can use Base64 library to convert string dictionary to bytes, and although you can convert bytes result to a dictionary using json library.您可以使用 Base64 库将字符串字典转换为字节,尽管您可以使用 json 库将字节结果转换为字典。 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))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM