简体   繁体   中英

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
for i in eval(dashboards.replace('false', 'False')):
    print(i['title'])

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

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"])

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']

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