Search code examples
pythonjsonpython-requestsnested

How to print nested JSON data using Python?


I just started programming. I'm trying to print some nested JSON data using a Python script.

Here's an example of the JSON:

{
"objects": [
        {
            "id": "1",
            "spec_version": "2.1",
            "type": "green",
            "extensions": {
                "extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba": {
                    "extension_type": "purple",
                    "id": "2",
                    "type": "yellow",
                    "created_at": "2023-09-26",
                    "updated_at": "2023-09-26",
                    "stix_ids": [
                        "3"
                    ],
                }
            }
       }
   ]
}

If I have to print something like the "extension_type" in "extensions", how can I do that? My Python script:

import json, requests 

url = "myUrl"

payload = {}
headers = {
  'Authorization': 'Auth',
  'Cookie': 'biscuit'
}

response = requests.request("GET", url, headers=headers, data=payload)
my_json = json.loads(response.text)

for data in my_json['objects'][0]['extensions']:
    print(data)

The output is: extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba I can only go so far, I don't know how to access the "extension_type" and print it.


Solution

  • data = {
    "objects": [
            {
                "id": "1",
                "spec_version": "2.1",
                "type": "green",
                "extensions": {
                    "extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba": {
                        "extension_type": "purple",
                        "id": "2",
                        "type": "yellow",
                        "created_at": "2023-09-26",
                        "updated_at": "2023-09-26",
                        "stix_ids": [
                            "3"
                        ],
                    }
                }
           }
       ]
    }
    

    You can access the extension_type in the data using the below piece of code:

    data["objects"][0]["extensions"]["extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba"]["extension_type"]