Good day
I have a basic Python class ToDoItem:
class ToDoItem:
def __init__(self, name, description, isComplete):
self.Name = name
self.Description = description
self.IsComplete = isComplete
If I instantiate an object of this type:
item = ToDoItem('cleanRoom', 'Clean my room', False)
'serialise' it to JSON:
itemJson = ujson.dumps(item)
and 'deserialise' it again:
item = ujson.loads(itemJson)
I get the following:
ValueError: syntax error in JSON
Is this the correct way to serialise an object to JSON?
JSON serialisation
Re: JSON serialisation
I believe json serialization is looking for a dictionary or array. I've always used a dictionary.
Curt
Curt
-
- Posts: 6
- Joined: Mon Apr 04, 2022 8:21 am
Re: JSON serialisation
Thank you, Curt
How do I get an object's properties into a dictionary?
How do I get an object's properties into a dictionary?
Re: JSON serialisation
Using your example:
There are other ways to organize this data.
curt
Code: Select all
item = {'Name' : 'cleanRoom',
'Description' : 'Clean my room',
'IsComplete' : False}
curt
Re: JSON serialisation
Change your class so the members have the exact same name as the arguments, then use __dict__ :
will print the same twice so both objects are the same.
Code: Select all
class ToDoItem:
def __init__(self, name, description, isComplete):
self.name = name
self.description = description
self.isComplete = isComplete
import json
toSerialize = ToDoItem('a', 'b', 'c')
print(toSerialize.__dict__)
deserialized = ToDoItem(**json.loads((json.dumps(toSerialize.__dict__))))
print(deserialized.__dict__)
-
- Posts: 6
- Joined: Mon Apr 04, 2022 8:21 am
Re: JSON serialisation
Thank you @stijn, works lovely...