0

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

3 Answers 3

1

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"])
Sign up to request clarification or add additional context in comments.

1 Comment

I am getting error as dashboards = eval(dashboardr.content) File "<string>", line 1, in <module> NameError: name 'false' is not defined
1

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

Comments

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

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

4 Comments

This is not enough to answer the question, it only fixes the second part of the question not how to parse the response.
When implemented i am getting error print(i['title']) TypeError: string indices must be integers, not str
With the eval function included i am getting ' for i in eval(a): File "<string>", line 1, in <module> NameError: name 'false' is not defined'
It's because you have a lower case "false" here instead of "False". You can fix this using the .replace method. Updated answer

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.