Skip to content

Add JSON to Object example? #6

@PythonCHB

Description

@PythonCHB

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions