简体   繁体   中英

Python 3 requests library and json within a list

For example I have this json response:

response = '{"data" : {"next_Data" : { "actual_data" :["data1", "data2", "data3"]}}}'

In my usual approach to a big amount of json, I do this:

import requests

for x in response.json()['data']['next_Data']:
    print x['actual_data']

#Output
>>> 'data1'
>>> 'data2'
>>> 'data3'

Now how do I manipulate the code to display which ever 'actual_data' I want? For example, I want the first record (in this case 'data1') to be the only one to be extracted..or I want the 3rd data ('data3') be the only one extracted..how do I do this?

Thanks a lot guys,

Drew

I'm going to fill out your code snippet a little more for future visitors with the same question. (Your snippet, by the way, will not print what you think it will.) It would look something like:

import requests

response = requests.get('http://example.com')
actual_data = requests.json()['data']['next_Data']['actual_data']

for x in actual_data:
    print x

# prints on separate lines data1, data2, data3


print actual_data
# prints ['data1', 'data2', 'data3']
print actual_data[0]
# prints data1
print actual_data[2]
# prints data3
print actual_data[1]
# prints data2
print actual_data[-1]
# prints data3
print actual_data[-2]
# prints data2
print actual_data[-3]
# prints data1

That's how you would access you array of data (actually a list as far as Python is concerned) once you have the array.

The access you described above, response.json()['data']['next_Data'] would return {'actual_data': ['data1', 'data2', 'data3']} and doing a for loop on that dictionary/hash/object would yield the key: 'actual_data' and trying x['actual_data'] would give you a TypeError since the indices are supposed to be integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM