jainilvachhani
jainilvachhani

Reputation: 914

How to get specific element from a JSON file in Python?

I am using The Guardian's API to get JSON data and now I want a specific element from the JSON data entry. How do I do that?

I am making the following GET request

url = 'http://content.guardianapis.com/search?from-date=2016-01-02&to-date=2016-01-02&order-by=newest&show-fields=all&page-size=1&api-key=API-KEY.

And now I want webTitle from the JSON data. So I am doing as follows:

response = requests.get(url)
response = response.content
response = json.loads(response)
content = response['response']['results']['webTitle']

But I am getting TypeError: string indices must be integers, not str error.

However, content = response['response']['results']works correctly.

Here is a spanshot of JSON data. enter image description here

Upvotes: 0

Views: 2125

Answers (4)

Sudheesh Singanamalla
Sudheesh Singanamalla

Reputation: 2297

response['response']['results'] provides you with a list of dictionaries. [{},{},...] where each dictionary contains the following in your example:

{id:'', type:'', sectionid:'', .... }

If you want the list of all the webTitle in the results you'd have to iterate over the list obtained from response['response']['results'] and select the webTitle or any other required key in the resulting dictionary. Here's an example

webTitleList = []
# Make the request for the JSON
results = response['response']['results']
for result in results:
    webTitleList.append(result['webTitle'])
# Now the webTitleList contains the list of all the webTitles in the returned json

However, you can also simplify the selection of the webTitle by using list comprehension on results. There are numerous examples on StackOverflow for the same.

Upvotes: 1

beenum
beenum

Reputation: 31

We get this error when we mistake a list with a dictionary. Seems like 'results' is actually a list with dictionary as its first item. Do the following instead.

content = response['response']['results'][0]['webTitle']

And obviously I assumed you have one item in the 'results' list only. If it has multiple items, iterate over the list.

Upvotes: 1

Mehdi
Mehdi

Reputation: 1360

response = request.get(url).json()
content = response['response']['results'][index]['webTitle']

Edit

Yes as Sudheesh Singanamalla suggests, results is a list and you You'd have to access a given index to get corresponding webTitle

Upvotes: 1

Rakesh
Rakesh

Reputation: 82785

results is a list. Iterate over it to fetch the required value.

Ex:

for i in response['response']['results']:
    print(i['webTitle'])

Upvotes: 0

Related Questions