-4

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

8
  • 1
    Please provide a minimal reproducible example and the full error traceback. Commented Mar 15 at 9:20
  • 1
    As your data is seemingly from a json file, you might want to delegate the things you are trying to do to the json built-in package Commented Mar 15 at 9:34
  • for item in d['cart']: print(item['id'])…? Commented Mar 15 at 9:56
  • I assume that the statement finalZero["items"]=each_items_in_json[''] is the one causing the problem. The subscript '' is not valid; what are you trying to do here? Commented Mar 15 at 10:38
  • @OldBoy kindly recheck the function i'm using, i have just updated it Commented Mar 15 at 11:23

2 Answers 2

1

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)       
Sign up to request clarification or add additional context in comments.

2 Comments

You can condense those first three lines to for items_in in respJson['cart']
@deceze thanks again for this quick suggestion, it worked better, and the code snippet looks more cool :)
0

If you have a set of conditions, you can use all (a Python built-in function).

import requests

response = requests.get(URL)  # update URL here
data = response.json()

for item in data["cart"]:
    if all([
        item["benefit_id"] != "-1",
        item["plan_id"] != "-1",
        item["change"] == 0
    ]):
        # generate new dictionary here

At this time, your example data does not provide any items that would satisfy your conditions.

2 Comments

Or just use the and operator…
it worked better with your suggestion , thank you again :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.