prompted by a question from a student in quarter 1, I cam up with this example of building an object from JSON: import json class AnObject: def __init__(self, name='', id=''): self.name = name self.id = id # this really should come from a file, or what's the point? JSON = """ {"name": "Fred", "id": "ABCD123" } """ obj = AnObject(**json.loads(JSON)) print(obj) print(obj.name) print(obj.id) # or the really dynamic way: class AnyObject: def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) obj = AnyObject(**json.loads(JSON)) print(obj) print(obj.name) print(obj.id) maybe a good example?
Activity