I am experimenting with fastapi and data from json files. When I add an object via app.put json.dumps adds an attribute "__pydantic_initialised__": true
to my new object.
I start with two users:
print(users)
{
'456rtz':
User(vname='Niemand', nname='Nixda', email='[email protected]',
role=3, mobile=0, street='', city='Zürich', zip=0, country='',
id='456rtz'),
'839f06fa-aa8c-4a77-9c5c-c036f913b18a':
User(vname='Paulchen', nname='Panther', email='[email protected]',
role=3, mobile=0, street='', city='', zip=0, country='',
id='839f06fa-aa8c-4a77-9c5c-c036f913b18a')
}
Then I add a user:
users[user.id] = user
print(users)
{
'456rtz':
User(vname='Niemand', nname='Nixda', email='[email protected]',
role=3, mobile=0, street='', city='Zürich', zip=0, country='',
id='456rtz'),
'839f06fa-aa8c-4a77-9c5c-c036f913b18a':
User(vname='Paulchen', nname='Panther', email='[email protected]',
role=3, mobile=0, street='', city='', zip=0, country='',
id='839f06fa-aa8c-4a77-9c5c-c036f913b18a'),
'3589f47b-79bf-4a3a-bc46-612386eed3e9':
User(vname='Tom', nname='Cat', email='[email protected]',
role=3, mobile=0, street='', city='', zip=0, country='',
id='3589f47b-79bf-4a3a-bc46-612386eed3e9')
}
To save all my users I convert this dictionary of User-objects to json like so:
dstring = json.dumps([vars(item) for item in users.values()], indent=4)
Just to make this point clear: The commands print(users)
, dstring=json.dumps(...
and the following print(dstring)
follow one another – nothing else is between them.
Now something very annoying happens: json.dumps adds an attribute "__pydantic_initialised__": true
to the new User-object-string in the json.dump:
print(dstring)
[
{
"vname": "Niemand",
"nname": "Nixda",
"email": "[email protected]",
"role": 3,
"mobile": 0,
"street": "",
"city": "Zurich",
"zip": 0,
"country": "",
"id": "456rtz"
},
{
"vname": "Paulchen",
"nname": "Panther",
"email": "[email protected]",
"role": 3,
"mobile": 0,
"street": "",
"city": "",
"zip": 0,
"country": "",
"id": "839f06fa-aa8c-4a77-9c5c-c036f913b18a"
},
{
"vname": "Tom",
"nname": "Cat",
"email": "[email protected]",
"role": 3,
"mobile": 0,
"street": "",
"city": "",
"zip": 0,
"country": "",
"id": "3589f47b-79bf-4a3a-bc46-612386eed3e9",
"__pydantic_initialised__": true
}
]
As my User-class has no attribute "pydantic_initialised" the program crashes when I try to read the users from file again.
What I find very strange: When I add multiple users one after another and then build the json, the dump adds this attribute to every new user.
Why does json.dumps do that, how does it distinguish the existing users from the new ones and – most important – how can I prevent it from doing so?
2
Answers
Thanks to all your help I found the solution: I added a dict-method to my dataclass:
Then
dstring = json.dumps([item.dict() for item in users.values()], indent=4)
works for my case as M.O. wrote.Using
vars(item)
will include internal fields to the Python class. Try using Pydantic’s.dict()
method instead: