user45706 user45706 - 2 years ago 88
Python Question

Read from list in contet

I'm very new to python and I'm trying to do a basic api request using the requests library, but I'm having some trouble reading a list in the returned body.

The body of my response looks like this:

"files": [{
"url": "http://someurl.json",
"lastModified": 1470924180000

With my code I get the data contained in "files", but I can't figure out how to get the data conatained in "url".

My code:

response = requests.get(url)
data = response.json()

This returns:

[{'url': 'http://myurl.json', 'lastModified': 1470928985000}]

How can I store the url and lastModified in variables?

Jim Jim
Answer Source

Simply with:

url = data['files'][0]['url']
last_modified = data['files'][0]['lastModified']

your data is a dictionary that contains a list of dictionaries for the "files" key. To get the first entry of files you must index the list with data['files'][0].

After that data['files'][0] is a dictionary which you can again access by key name as required, in this case 'url' and 'lastModified'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download