Page 1 of 1

namedtuple to JSON possible?

Posted: Thu Jan 10, 2019 9:10 pm
by Polo
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

Then I thought of:

Code: Select all

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

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

    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?

Re: namedtuple to JSON possible?

Posted: Fri Jan 11, 2019 8:19 am
by pythoncoder
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()

Re: namedtuple to JSON possible?

Posted: Fri Jan 11, 2019 11:48 am
by Polo
Yes! That works.
Thank you very much!