Someguywhocodes
Someguywhocodes

Reputation: 781

Accessing nested values

I want to move data from one table to another with some processing in-between. The data is a large Json object at it's source so I'm looking to strip out individual values are selecting the data. I pass the data into the below function row by row.

def transformBadges(row):
    for inner_row in row:
        for element in inner_row :
            id = element['id']
            archived = element['archived']
            type = element['type']
            name = element['name']
            badge_id = str(uuid.uuid4())

            insertBadge(id, archived, type, name, badge_id)

row contains my target column, essentially. However I've updated my select to select a few more columns. Due to this I had to change the above code to the below:

def transformBadges(row):
    badges = row['badges']
    for inner_row in badges:
        for element in inner_row:
            id = element['id']
            archived = element['archived']
            type = element['type']
            name = element['name']
            badge_id = str(uuid.uuid4())

            insertBadge(id, archived, type, name, badge_id)

In my mind, it's the exact same - just now with the data stored in a different variable. However, I get this error:

Traceback (most recent call last):
  File "etl/main.py", line 537, in <module>
    main()
  File "etl/main.py", line 99, in main
    transformBadges(row)
  File "etl/main.py", line 106, in transformBadges
    id = element['id']
TypeError: string indices must be integers

Why would the first work but not the second?

Upvotes: 2

Views: 45

Answers (1)

SalaryNotFound
SalaryNotFound

Reputation: 224

def transformBadges(row):
    badges = row['badges']
    for element in badges:
        id = element['id']
        archived = element['archived']
        type = element['type']
        name = element['name']
        badge_id = str(uuid.uuid4())

        insertBadge(id, archived, type, name, badge_id)

Because badges now is one inner_row already

Upvotes: 2

Related Questions