skip to Main Content

I was wondering if someone could tell me what I’m doing wrong.
Below is a sample json I’m looking to extract the value in the ‘details’ list, but for some reason I just can’t figure out how to achieve it.

For example I want to get the item from the list that matches ‘DEF5678’. But i keep getting error.

Here’s how I was trying to access it:

payload  = {"name": "John",
           "age": 30,
           "city": "New York",
           "details": [
                        {"ABC1234": 
                          {"name": "Office mover",
                          "ratings": "poor"}
                          },

                        {"DEF5678": 
                          {"name": "Installer",
                          "ratings": "good"}
                        }
                      ],
                      "id": "XYZ12344",
                      "type": "hire"
             }
payload = json.loads(payload)
for i in payload["details"]:
    if i['DEF5678'] is not None:
        print(i)

It say’s keyerror: ‘DEF5678’

Can someone please help, thanks

2

Answers


  1. The issue is that json.loads() is used to parse a JSON string and convert it into a Python object. However, in your code, the payload variable is already a Python object and doesn’t need to be loaded from JSON.

    To access the value in the ‘details’ list that matches ‘DEF5678’, you need to loop through the list and check the keys of each dictionary:

    payload = {
       "name": "John",
       "age": 30,
       "city": "New York",
       "details": [
          {
             "ABC1234": {
                "name": "Office mover",
                "ratings": "poor"
             }
          },
          {
             "DEF5678": {
                "name": "Installer",
                "ratings": "good"
             }
          }
       ],
       "id": "XYZ12344",
       "type": "hire"
    }
    
    for item in payload["details"]:
        if "DEF5678" in item:
            print(item["DEF5678"])
    

    Output:

    {'name': 'Installer', 'ratings': 'good'}
    
    Login or Signup to reply.
  2. if your payload is in string then you have to convert to python object using json.loads() but it seems like payload is already python object so you don’t have to convert to python object. you can directly use key of payload.

    for obj in payload["details"]:
       if "DEF5678" in obj:
           print(obj)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search