-1

my problem is that I want to get data (JSON) from a database and put it into a new JSON structure to UPDATE a table. Like parsing. Now I have this code:

for x in range(len(data_set)):
    data = json.loads(data_set[x][1])
    items = []
    item = {}

    try:
        for weapon in data['weapons']:
            item['type'] = 'item_weapon'
            item['name'] = weapon['name'] # overwrites items[]
            item['count'] = weapon['ammo']
            items.append(item)
            #item.clear() # also overwrites items ????
            print(items)
            # print(weapon['label'])
    except Exception:
        #print("No weapons found")
        pass

I can navigate thru my data and everything works. Until I have 2 or more items to append, which means that the inner for-loop is running >1 times. Then the new item is overwriting the whole items[] list before it uses items.append(item). At the end I get the exact amount of item ind items. But its overwritten with the last item. Output is:

        {
            "count": 51242,
            "name": "black_money",
            "type": "item_account"
        },
        {
            "count": 51242,
            "name": "black_money",
            "type": "item_account"
        },
        ...

but this should be two different items. But at item['name'] = weapon['name'] # overwrites items[] all "old" items are overwritten.

onezero
  • 31
  • 4

1 Answers1

0

The issue is that item is defined outside the loop. What you are doing inside the loop is get a reference ("pointer" of sorts) to the same dict item, modifying its details, and appending the same reference of item to the list. Meaning, your list contains multiple references to the exact same object.

To fix this: define item inside the loop instead, so that a new item object is created at each iteration.

for x in range(len(data_set)):
    data = json.loads(data_set[x][1])
    items = []

    try:
        for weapon in data['weapons']:
            item = {}
            item['type'] = 'item_weapon'
            item['name'] = weapon['name'] # overwrites items[]
            item['count'] = weapon['ammo']
            items.append(item)
            #item.clear() # also overwrites items ????
            print(items)
            # print(weapon['label'])
    except Exception:
        #print("No weapons found")
        pass
Anis R.
  • 6,656
  • 2
  • 15
  • 37