Skip to content
Advertisement

how to parse json array in django

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.

    req = requests.get('https://api.coursera.org/api/courses.v1?q=search&
                                query=machine+learning')
    jsonList = []
    jsonList.append(req.json())
    print(jsonList[0])
    userData = {}
    for value in jsonList[0]:
        parsedData.append(value["name"])
        print(value["name"])
    return render(request, 'app/profile.html', {'data': parsedData})

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`):

import requests
import json

req = requests.get('https://api.coursera.org/api/courses.v1?q=search&query = machine + learning')

json_data = json.loads(req.text)

for element in json_data['elements']:
    print(element['name'])

>> Speak English Professionally: In Person, Online & On the Phone
   Machine Learning
   Learning How to Learn: Powerful mental tools to help you master tough subjects
   .
   .

Update:

To display the names in a view:

Considering that you have a very basic template:

{% for name in names %}
    <p>{{ name }}</p>
{% endfor %}

Inside your view, considering you already have the above code, and you stored all the names in a list called names:

return render(request, 'app/profile.html', context={'names': names}, status=200)  
# it's always a good habit to return an HTTP status code 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement