Home > Software engineering >  json loop from model in Django
json loop from model in Django

Time:01-06

How would I be able to create a loop on items, to further build up more items values.

this is how my json looks, just not sure on the on the loop part to add extra items to the json_data so 1 or 20 items could be sent

json_data = {
        'data': {
            'type': 'Delivery',
            'customer_feedback': None,
            'warehouse_address': None,
            'items': [
                {
                    'id': '5b22055510c92b1a046ece21',
                    'sku': '12387654',
                    'quantity': 8,
                },
                {
                    'id': '5b22055510c92b1a046ece06',
                    'sku': '12387654',
                    'quantity': 5,
                },
            ],
        },

    response = requests.post('https://api.url', headers=headers, json=json_data)

CodePudding user response:

You can do it using a for loop and append;

json_data = {
        'data': {
            'type': 'Delivery',
            'customer_feedback': None,
            'warehouse_address': None,
            'items': [
                {
                    'id': '5b22055510c92b1a046ece21',
                    'sku': '12387654',
                    'quantity': 8,
                },
                {
                    'id': '5b22055510c92b1a046ece06',
                    'sku': '12387654',
                    'quantity': 5,
                },
            ],
        },
    }
    new_items = [{"id": "2323", "sku": "32423432", "quantity": 3},{"id": "4565", "sku": "564556", "quantity": 4}]
    for i in new_items:
        json_data["data"]["items"].append(i)

    print(json_data)

In this example the new items are in a dictionary. We iterate over the dictionary with a for loop and append the new items to the json object.

The print result will look like this;

{'data': {'type': 'Delivery', 'customer_feedback': None, 'warehouse_address': None, 'items': [{'id': '5b22055510c92b1a046ece21', 'sku': '12387654', 'quantity': 8}, {'id': '5b22055510c92b1a046ece06', 'sku': '123
87654', 'quantity': 5}, {'id': '2323', 'sku': '32423432', 'quantity': 3}, {'id': '4565', 'sku': '564556', 'quantity': 4}]}}
  • Related