namedtuple to JSON possible?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Polo
Posts: 10
Joined: Tue Oct 02, 2018 1:07 pm

namedtuple to JSON possible?

Post by Polo » Thu Jan 10, 2019 9:10 pm

Hello everyone. I've been trying to find a good way to serialize objects, but there's always something missing in the micropython implementation.
My goal is a Setting class where:
- I can access parameters by name (not key lookup)
- I can serialize the parameters to JSON
Something that can do: object.param <--> dict['param']

I thought I could use namedtuples, but micropython doesn't do:

Code: Select all

namedtuple._asdict()
Then I thought of:

Code: Select all

settings_dict = {"param": 1}  # loaded from JSON

class Setting(object):
    def __init__(self):
        self.param = None
        self.__dict__.update(settings_dict)

    def save(self):
        global settings_dict
        settings_dict = self.__dict__
        # save to json
But this doesn't work because __dict__.update doesn't do anything in micropython

Am I missing the obvious or is there no clean way of doing this?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: namedtuple to JSON possible?

Post by pythoncoder » Fri Jan 11, 2019 8:19 am

Is this any use?

Code: Select all

settings_dict = {"param": 1, "bar":99}  # loaded from JSON

class Foo:
    def __init__(self):
        for k in settings_dict.keys():
            setattr(self, k, settings_dict[k])

foo = Foo()
foo.param
foo.bar
Peter Hinch
Index to my micropython libraries.

Polo
Posts: 10
Joined: Tue Oct 02, 2018 1:07 pm

Re: namedtuple to JSON possible?

Post by Polo » Fri Jan 11, 2019 11:48 am

Yes! That works.
Thank you very much!

Post Reply