I have access to an outside API which have some data something like the following:
{
"Successful":true,
"Message":"[{\"Id\":1,\"GroupId\":0,\"QuestionTitle\":\"What is your first name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]},{\"Id\":2,\"GroupId\":0,\"QuestionTitle\":\"And your last name?\",\"GroupName\":null,\"QuestionType\":\"TEXT\",\"IsMappingAvailable\":null,\"BodyRegion\":0,\"EnableCalculation\":false,\"Responses\":[]}]"
}
Now I want to show all these Id
and QuestionTitle
in my template.
my views.py
:
def GetQuestion(request):
headers = {'Content-Type': 'application/json', 'Authorization': 'Basic XXXXXXXXXX='}
body = { "Tenant" : "devED" }
GetQuestion_response = requests.post('https://url_name.com/api/GetQuestions', headers=headers, json=body).json()
GetQuestion_dict={
'GetQuestion_response' : GetQuestion_response,
}
return render(request, 'app\GetQuestion.html', GetQuestion_dict)
in my template
:
{% for i in GetQuestion_response.Message %}
<h2>ID: {{ i.Id }}</h2>
<h2>QuestionTitle: {{ i.QuestionTitle }}</h2>
{% endfor %}
But unfortunately, it shows no results. Maybe it's because the value of the Message
key in the API is inside the double quote (like a string).
Please suggest how can I fix this?
CodePudding user response:
In this case since Message
is returned as a string, it needs to be parsed again as json like this:
import json
def GetQuestion(request):
headers = {'Content-Type': 'application/json', 'Authorization': 'Basic XXXXXXXXXX='}
body = { "Tenant" : "devED" }
GetQuestion_response = requests.post('https://url_name.com/api/GetQuestions', headers=headers, json=body).json()
# Parse message as json
GetQuestion_response = json.loads(GetQuestion_response['Message'])
GetQuestion_dict={
'GetQuestion_response' : GetQuestion_response,
}
return render(request, 'app\GetQuestion.html', GetQuestion_dict)
And then in the template, just use GetQuestion_response
:
{% for i in GetQuestion_response %}
<h2>ID: {{ i.Id }}</h2>
<h2>QuestionTitle: {{ i.QuestionTitle }}</h2>
{% endfor %}