SG131712
SG131712

Reputation: 135

How filter required data from response of a request by using Python

I have some response of a get request stored in a variable as below...

dashboard = 'http://12.345.67.890:8000/api/search?query=&starred=false'
dashboardr = s.get(dashboard)
dashboards = dashboardr.content
print(dashboards)

The response looks as below...

[{"id":19,"title":"Apple","uri":"db/abc-api","type":"dash-db","tags":[],"isStarred":false},{"id":20,"title":"Banana","uri":"db/cde-api","type":"dash-db","tags":[],"isStarred":false},{"id":7,"title":"Mango","uri":"db/efg","type":"dash-db","tags":[],"isStarred":false}]

Can some one please help me how we can extract the values of title and stored in another variable?

Title values in the above response are

Apple
Banana
Mango

Upvotes: 0

Views: 4473

Answers (3)

Ninad Gaikwad
Ninad Gaikwad

Reputation: 4480

for i in eval(dashboards.replace('false', 'False')):
    print(i['title'])

instead of printing title you can save it in a list variable.

Upvotes: 1

balderman
balderman

Reputation: 23815

Assuming that the response you from the HTTP call is a string, the code below extract the titles.

import json

response_str = '[{"id": 19, "title": "Apple", "uri": "db/abc-api", "type": "dash-db", "tags": [], "isStarred": false},{"id": 20, "title": "Banana", "uri": "db/cde-api", "type": "dash-db", "tags": [], "isStarred": false},{"id": 7, "title": "Mango", "uri": "db/efg", "type": "dash-db", "tags": [], "isStarred": false}]'
response_dict = json.loads(response_str)
titles = [entry['title'] for entry in response_dict]
print(titles)

Output:

[u'Apple', u'Banana', u'Mango']

Upvotes: 1

rkp768
rkp768

Reputation: 56

Use eval(dashboards) instead of dashboards.

dashboard = 'http://12.345.67.890:8000/api/search?query=&starred=false'
dashboardr = s.get(dashboard)
# eval() will convert a string to a python statement/expression
dashboards = eval(dashboardr.content)

title_list = []
for _ in dashboards:
   title_list.append(dashboards["title"])

Upvotes: 1

Related Questions