JSON serialisation

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
emile.cronje
Posts: 6
Joined: Mon Apr 04, 2022 8:21 am

JSON serialisation

Post by emile.cronje » Sat Jul 02, 2022 2:35 pm

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?

User avatar
curt
Posts: 25
Joined: Thu Jul 29, 2021 3:52 am
Location: Big Lake, Alaska

Re: JSON serialisation

Post by curt » Sat Jul 02, 2022 3:45 pm

I believe json serialization is looking for a dictionary or array. I've always used a dictionary.
Curt

emile.cronje
Posts: 6
Joined: Mon Apr 04, 2022 8:21 am

Re: JSON serialisation

Post by emile.cronje » Sat Jul 02, 2022 4:00 pm

Thank you, Curt

How do I get an object's properties into a dictionary?

User avatar
curt
Posts: 25
Joined: Thu Jul 29, 2021 3:52 am
Location: Big Lake, Alaska

Re: JSON serialisation

Post by curt » Sat Jul 02, 2022 5:17 pm

Using your example:

Code: Select all

item = {'Name' : 'cleanRoom',
	'Description' : 'Clean my room',
	'IsComplete' : False}
There are other ways to organize this data.
curt

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: JSON serialisation

Post by stijn » Sun Jul 03, 2022 10:47 am

Change your class so the members have the exact same name as the arguments, then use __dict__ :

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__)
will print the same twice so both objects are the same.

emile.cronje
Posts: 6
Joined: Mon Apr 04, 2022 8:21 am

Re: JSON serialisation

Post by emile.cronje » Sun Jul 03, 2022 8:32 pm

Thank you @stijn, works lovely...

Post Reply