0

This question may be opinion based, but I figured I'd give it shot.

I am attempting to create a variety of classes which gets its values from JSON data. The JSON data is not under my control so I have to parse the data and select the values I want. My current implementation subclasses UserDict from python3's collection module. However, I have had iterations where I have directly created attributes and set the values to the parsed data.

The reason I changed to using the UserDict is the ease of using the update function.

However, I feel odd calling the object and using MyClass['attribute'] rather than MyClass.attribute

Is there a more pythonic way to model this data?

1 Answer 1

1

I am not 100% convinced that this makes sense, but you could try this:

class MyClass (object):
    def __init__(self, **kwargs):
        for key in kwargs.keys():
            setattr(self, key, kwargs[key])

my_json = {"a":1, "b":2, "c":3}

my_instance = MyClass(**my_json)

print (my_instance.a)
# 1
print (my_instance.b)
# 2
print (my_instance.c)
# 3

--- edit

in case you have nested data you could also try this:

class MyClass (object):
     def __init__(self, **kwargs):
         for key in kwargs.keys():
              if isinstance(kwargs[key],dict):
                  setattr(self, key, MyClass(**kwargs[key]))
              else:
                  setattr(self, key, kwargs[key])

my_json = {"a":1, "b":2, "c":{"d":3}}

my_instance = MyClass(**my_json)

print (my_instance.a)
# 1
print (my_instance.b)
# 2
print (my_instance.c.d)
# 3
Sign up to request clarification or add additional context in comments.

4 Comments

For nested data it would return a dictionary. You could also create new classes for each nested object. See my edited answer above.
isinstance(kwargs[key],dict) still doesn't capture arrays, but this is going in a good direction. There's also the problem of checking the type of value (isinstance(myinstance.a, int)) - this could develop into an actual library.
Yep, I think I stop here. You should get the point and can go from here. I am still not convinced that this all makes sense. If you don't know the structure of you json, why create a class? If schemas of different json objects differ, you would end up with two class instances with different interfaces.
Essentially I'm modeling sports data. I know what exact data I'm getting, it just has data that I don't need to hang on to. I just meant that I can't change the structure so I have to manually parse the JSON. Different classes hold different data. For example I have a class that models just a game's overall stats i.e. team names, score and that's it. I have another class that models the full statistics of a game.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.