0

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

4 Answers 4

1
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

Sign up to request clarification or add additional context in comments.

1 Comment

This wouldn't work since results is a list. You'd have to access a given index [0],[1] etc..
1

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.

Comments

1

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.

1 Comment

Please mark one of the answers as accepted in case they helped you so that the question could be marked as closed.
0

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

Ex:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.