Python:将字典转换为字节 [英] Python: Convert dictionary to bytes

查看:623
本文介绍了Python:将字典转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字典转换为字节,但是在将其转换为正确格式时遇到问题。

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)

我的字典结构如下-

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

同时, schema.loads 期望输入是str,bytes或bytearray。以下是我将字典转换为字节的步骤

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)

输出:

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?

推荐答案

您可以使用 json.dumps()中的> indent 选项以获得 \n 符号:

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)

输出:

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

这篇关于Python:将字典转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆