user3923278 user3923278 - 6 months ago 36
Python Question

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 display "name" which is inside "elements" json array.I have used this code but didnot worked for me.this is the json that i am getting

{
"elements": [
{
"id": "H02KsW1DEeWXrA6ju0fvnQ",
"courseType": "v2.ondemand",
"slug": "practical-machine-learning",
"name": "Practical Machine Learning"
},
{
"id": "qi9mnkIJEeWC4g7VhG4bTQ",
"courseType": "v2.ondemand",
"slug": "ml-foundations",
"name": "Machine Learning Foundations: A Case Study Approach"
}],
"paging": {
"next": "100",
"total": 684,
"facets": {
"courseType": {
"facetEntries": [
{
"id": "v2.ondemand",
"name": "On Demand",
"count": 476
},
{
"id": "v1.session",
"name": "Sessions",
"count": 158
}
]
},
"subdomains": {
"facetEntries": [
{
"id": "personal-development",
"name": "Personal Development",
"count": 55
},
{
"id": "other-languages",
"name": "Other Languages",
"count": 3
},
{
"id": "algorithms",
"name": "Algorithms",
"count": 25
}]
}
}


And here is the code that i have used to parse

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})

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
   .
   .
Comments