See also
hasattr.
"""
json2object.py
Convert a string that looks like a dictionary into a Python object
with attributes.
"""
import sys
import json #JavaScript Object Notation
#Assume we have downloaded this JSON-format string from a server.
s = """\
{
"name": "Mark",
"age": 64,
"favorite years": [1965, 1982, 1995],
"IKEA language": {"Billy": "bookcase", "Sladda": "bike", "Klippan": "sofa"}
}"""
#Convert the string of characters into a dictionary.
try:
dictionary = json.loads(s)
except json.JSONDecodeError as error:
print(error)
sys.exit(1)
#Copy the keys and values of the dictionary into a Python object of class Person.
class Person(object):
pass
person = Person() #Create an object of type Person.
for key, value in dictionary.items():
setattr(person, key, value)
#Print the Python object to make sure it's okay.
for key in person.__dict__:
print(key, getattr(person, key))
sys.exit(0)
name Mark
age 64
favorite years [1965, 1982, 1995]
IKEA language {'Billy': 'bookcase', 'Sladda': 'bike', 'Klippan': 'sofa'}
Note that at the end of the program we could have said
print(person.name)but we could not have said
print(person.favorite years)because
favorite years
is not a valid Python
identifier.
person
have any methods?
We will discover that
person
has many methods, inherited form the base class
object.
In the following code,
attributes
is a
list
of
strings
containing the names of all the attributes of
person.
Some of these attributes are variables and some are methods.
methods
is a
list
of
strings
containing the names of the attributes that are methods.
attributes = dir(person) methods = [attribute for attribute in attributes if callable(getattr(person, attribute))] #also try if not callable for i, method in enumerate(methods, start = 1): print(f"{i:2} {method}")
1 __class__ 2 __delattr__ 3 __dir__ 4 __eq__ 5 __format__ 6 __ge__ 7 __getattribute__ 8 __gt__ 9 __hash__ 10 __init__ 11 __init_subclass__ 12 __le__ 13 __lt__ 14 __ne__ 15 __new__ 16 __reduce__ 17 __reduce_ex__ 18 __repr__ 19 __setattr__ 20 __sizeof__ 21 __str__ 22 __subclasshook__