I'm learning Python and I'm messing around with API calls and Json responses. I want to turn the response into objects. My approach is to iterate through the json response using nested loops and for each json object create a python object.
The json response contains a number of families, and each family has a number of family members. The problem is that when I turn them into python objects, each family gets ALL the members from ALL the families. I guess it has something to do with the scopes in the loops, but I can't figure out the right way to approach this.
All help would be appreciated:
The json response:
families_from_api = """{
"success":true,"data":[
{
"family":"Anderson","members":[
{"name":"Roger","age":36},
{"name":"Alice","age":"24"},
{"name":"Sammy","age":12}
]
},
{
"family":"Lindquist","members":[
{"name":"Martin","age":52},
{"name":"Lukas","age":"46"},
{"name":"Anne","age":20}
]
}
]
}
"""
# Pythonize the response
families_info = json.loads(families_from_api)
families = families_info['data']
The classes:
class Member:
name = ""
age = 0
class Family:
name = ""
members = []
Iterating through the response and creating objects:
# Array to store all families
all_families = []
# Iterate through the response and turn into objects
for family in families:
f = Family()
f.name = family['family']
for member in family['members']:
m = Member()
m.name = member['name']
m.age = member['age']
f.members.append(m)
# Append the created family object to an array
all_families.append(f)
Printing my objects:
# Iterate through objects and print families and members
for family in all_families:
print("Family name:", family.name, "has these members:")
for member in family.members:
print("Name:", member.name, "Age", member.age)
The result:
Family name: Anderson has these members:
Name: Roger Age 36
Name: Alice Age 24
Name: Sammy Age 12
Name: Martin Age 52
Name: Lukas Age 46
Name: Anne Age 20
Family name: Lindquist has these members:
Name: Roger Age 36
Name: Alice Age 24
Name: Sammy Age 12
Name: Martin Age 52
Name: Lukas Age 46
Name: Anne Age 20