pythonarraysdictionaryiteration

Iterating over JSON containing lists of dictionaries in python


Please help in providing a solution to iterate through a JSON response containing lists of dictionaries in python:

{
"cart": [
    {
        "id": "0Zy2jwLzQzlk7xq3",
        "benefit_id": "-1",
        "plan_id": "-1",
        "change": 5,
        "change_at": "2025-03-13 15:03:00+05:30",
        "nominees": [],
        "dependents_ids": [],
        "upload_nominees_form": null,
        "mid_term": false,
        "endorsement_id": "OJ1xzPR8N2V0gMbd",
        "premium_value": 0.0,
        "sum_insured": 0,
        "annual_premium": 0.0,
        "employer_premium": 0.0,
        "added_by": 0
    },
    {
        "id": "J1xzPR8JmLV0gMbd",
        "benefit_id": "-1",
        "plan_id": "-1",
        "change": 4,
        "change_at": "2025-03-13 15:03:05+05:30",
        "nominees": [],
        "dependents_ids": [],
        "upload_nominees_form": null,
        "mid_term": false,
        "endorsement_id": "OJ1xzPR8N2V0gMbd",
        "premium_value": 0.0,
        "sum_insured": 0,
        "annual_premium": 0.0,
        "employer_premium": 0.0,
        "added_by": 0
    }],
    "complete_cart": [{"modified":"false"}]
 }

I am using a for loop to iterate through the values, but is getting below error:

TypeError: string indices must be integers, not 'str'

Please see below code i'm in, i am trying o build a fresh dictionary where if "benefit_id" is not "-1", if "plan_id" is not "-1" , if "change" is 0 then create a json:

def userCompleteCart(self):
     response=self.client.get(url=GET_userCart.userCart_EndPoint)    
     respJson=response.json()
     storeListsItemsFromJSON={}
     JSONtoUseInNextAPI={}
     for each_items_in_json in respJson:
         if each_items_in_json=='cart':
             for items_in in each_items_in_json:
                 if items_in['benefit_id']!='-1':
                     if items_in['plan_id']!='-1':
                         if items_in['change']== 0:
                             if items_in['id'] is not None:
                                storeListsItemsFromJSON["user_id"]=items_in['id']
     storeListsItemsFromJSON["mid-term"]= False      
     JSONtoUseInNextAPI=json.dumps(storeListsItemsFromJSON)                    
     print(JSONtoUseInNextAPI)

     response=self.client.post(url="api/user/complete-cart",data=JSONtoUseInNextAPI)
     if(response.status_code==200):
      # print("[API_CALL]: Success call POST/user-complete-cart API:",response.status_code)
      print("\033[92m {}\033[00m".format("[API_CALL]: Success call POST/user-complete-cart API:"),response.status_code)          
     else:
      # print("Failed call for POST/user-complete-cart API",response.status_code) 
      print("\033[91m {}\033[00m".format("[FAIL_CASE]: Failed call for POST/user-complete-cart API !!"),response.status_code)
      

**Note: I want to create this dictionary (JSONtoUseInNextAPI) as a JSON request for the next API


Solution

  • I would like to thank each one of you, who spared time for going through the problem statement. As a part of good gesture, i am posting the final code-snippet that worked for me, after suggestions by @ekhumoro, @OldBoy , @KlausD, @deceze

     for key, each_items_in_json in respJson.items():  ---suggested changes by @ekhumoro
                 if key=='cart': ---suggested changes by @ekhumoro
                        for items_in in each_items_in_json:
                         if items_in['benefit_id']!='-1':
                             if items_in['plan_id']!='-1':
                                 if items_in['change']== 0:
                                     if items_in['id'] is not None:
                                        storeListsItemsFromJSON["user_id"]=items_in['id']
             storeListsItemsFromJSON["mid-term"]= False      
             JSONtoUseInNextAPI=json.dumps(storeListsItemsFromJSON)