Parse json fields to variables

I’m trying to parse fields of a json output from an API query.

Example json:

         "Type":"WHOIS servers",

I want to parse some fields, and get something like:

FoundDate: 2021-08-16T14:51:17.747Z"

so I tried this, but didn’t work: Selecting fields from JSON output

This is my python code:

import requests
import json

#UserID + Api Key
auth = ('USERID','APIKEY')
headers = {    'Content-Type': "application/json",    }

url = "
alerts = requests.request("GET", url, auth = auth, headers=headers)

for alertID in alerts.text.split('","'):
  url = ""+alertID #<-----This is the request that extract the JSON
  alertDetails = requests.request("GET", url, auth = auth, headers=headers)

  dict = alertDetails.text
  url=dict['Assets'][0]['Value'] #<---------Trying to parse the desired value

This is the result:

Traceback (most recent call last):
  File "", line 73, in <module>
TypeError: string indices must be integers

Any suggestion?


First you need to parse the JSON that comes as response.

data = alertDetails.json() # use convenience method

Then access fields you want like a nested dict.

url = data['Details']['Source'].get('URL')
print (f'Phishing URL: {url}')
found_date = data.get('FoundDate')
print(f'Found date: {found_date}')

This assumes (based on error you show) that Deatails and Source will always be present, ony URL key may be missing. To be on the safe side you can do

url = data.get('Details', {}).get('Source', {}).get('URL')
print (f'Phishing URL: {url}')

or use try/except:

    url = data['Details']['Source']['URL']
except KeyError:
    url = None
print (f'Phishing URL: {url}')