Home > front end >  How to add further items to JSON in a loop
How to add further items to JSON in a loop

Time:01-06

I am not sure on the on the loop part to add extra items to below JSON in json_data.

I want to add 1 or 20 items before sending the request.

Code

json_data contains my JSON structure.

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

# before posting I want to add additional items

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

I thought about append, but does it not just add to the bottom? How can I append extra items containing id , sku and quantity values? How to create a loop on items, to further build up and add more items values?

CodePudding user response:

You can do it using a for loop and append() to the List;

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

# collect items to add in a list
new_items = [
  {"id": "2323", "sku": "32423432", "quantity": 3},
  {"id": "4565", "sku": "564556", "quantity": 4}
]

# add each of them to the items inside your JSON structure
for i in new_items:
    json_data["data"]["items"].append(i)

print(json_data)

In this example the new items are in a list new_items, each item is represented as a dictionary. We iterate over the list new_items with a for loop and append the new items to the JSON object at the desired location - inside 'data', there to the 'items' list.

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