skip to Main Content

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.

3

Answers


  1. data is a dictionary object

    for data in my_json['objects'][0]['extensions']:
        print(data['extension_type'])
    
    Login or Signup to reply.
  2. 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"]
    
    Login or Signup to reply.
  3. I presume you know the keys as far as extensions, but the next key is dynamic and unknown to you. In that case, you can follow this procedure to get the extension_type value:

    Since my_json['objects'][0]['extensions'] is a dict, you can find the first (and in this case only) value in the dict using:

    ext = next(iter(my_json['objects'][0]['extensions'].values()))
    

    and then simply get the extension:

    ext_type = ext['extension_type']
    

    Output:

    'purple'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search