Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to serialize the python object with the Marshmallow schema. Following is the schema I have set for my data.

from marshmallow import Schema, fields

1 (647)

class User:

    def __init__(self, name = None, age = None, is_active = None, details = None):

        self.name = name

        self.age = age

        self.is_active = is_active

        self.details = details

class UserSchema(Schema):

    name = fields.Str()

    age = fields.Int()

    is_active = fields.Bool()

    details = fields.Dict()

The input of the code is in dictionary format and all the elements will be in string.

user_data = {"name":"xyz", "age":"20", "is_active": 'true',"details":"{'key1':'val1', 'key2':'val2'}"}

When I try to execute the below code, values of age and is_active got converted into respective datatype but details remains unchanged.

user_schema = UserSchema()

user_dump_data = user_schema.dump(user_data)

print(user_dump_data)

Output:

{'name': 'xyz', 'is_active': True, 'details': "{'key1':'val1', 'key2':'val2'}", 'age': 20}

I need to serialize the input data into the corresponding datatype.

1 Answer

0 votes
by (108k points)

I think you are getting confused between serializing (dumping) and deserializing (loading).

See, the Dumping process is progressing from object form to json-serializable basic python classes with the help of Schema.dump) or json string (using Schema.dumps). Loading on the other hand is a reverse operation. Generally, your API loads the data from the external world and dumps your objects to the outer world.

If your input information is this data and you want to load it into objects, you need to use load, not dump.

user_data = {"name":"xyz", "age":"20", "is_active": 'true',"details":"{'key1':'val1', 'key2':'val2'}"}

user_loaded_data = user_schema.load(user_data)

user = User(**user_loaded_data)

Except if you do so, you'll get some another issue. DictField expects data as a dict, not a str. You need to enter the below code:

user_data = {"name":"xyz", "age":"20", "is_active": 'true',"details": {'key1':'val1', 'key2':'val2'}}

If you are a total beginner and wish to learn Python, then do check out the below python tutorial video for better understanding:

Related questions

0 votes
1 answer
asked Dec 4, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...