0

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
  • if you're only holding data in those classes, you might want to look into [dataclasses](https://docs.python.org/3/library/dataclasses.html) – njzk2 Oct 22 '20 at 20:24

2 Answers2

1

when you assign a class attribute like you where doing, it is global across all instances of that class, so you should use instance attributes instead.

class Member:
    def __init__()
        name = ""
        age = 0

class Family:
    def __init__()
        name = ""
        members = []
Hadrian
  • 917
  • 5
  • 10
1

Your classes are lacking the init method that is automatically called when the constructor is called

When a class defines an init() method, class instantiation automatically invokes init() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:

(from https://docs.python.org/3/tutorial/classes.html)

Your code should be, for the classes

class Member:
    def __init__(self):
         self.name = ""
         self.age = 0


class Family:
    def __init__(self):
        self.name = ""
        self.members = []
vidu.sh
  • 537
  • 1
  • 3
  • 21