I am new in django rest api framework and using get i am fetching the a json array whose api is this https://api.coursera.org/api/courses.v1?q=search&query=machine+learning and i am not able to parse it.Actually i want to store all the names and send them to .html file .I have used this code but didnot worked for me.
JavaScript
x
11
11
1
req = requests.get('https://api.coursera.org/api/courses.v1?q=search&
2
query=machine+learning')
3
jsonList = []
4
jsonList.append(req.json())
5
print(jsonList[0])
6
userData = {}
7
for value in jsonList[0]:
8
parsedData.append(value["name"])
9
print(value["name"])
10
return render(request, 'app/profile.html', {'data': parsedData})
11
Advertisement
Answer
This actually has nothing to do with Django.
The way to get to the name
attribute inside elements
(there are actually many elements, each one has a ‘name`):
JavaScript
1
16
16
1
import requests
2
import json
3
4
req = requests.get('https://api.coursera.org/api/courses.v1?q=search&query = machine + learning')
5
6
json_data = json.loads(req.text)
7
8
for element in json_data['elements']:
9
print(element['name'])
10
11
>> Speak English Professionally: In Person, Online & On the Phone
12
Machine Learning
13
Learning How to Learn: Powerful mental tools to help you master tough subjects
14
.
15
.
16
Update:
To display the names in a view:
Considering that you have a very basic template:
JavaScript
1
4
1
{% for name in names %}
2
<p>{{ name }}</p>
3
{% endfor %}
4
Inside your view, considering you already have the above code, and you stored all the names in a list called names
:
JavaScript
1
3
1
return render(request, 'app/profile.html', context={'names': names}, status=200)
2
# it's always a good habit to return an HTTP status code
3