[Django]-Django- Json data in template

3👍

To iterate, you need it to be a python dict object and not the JSON string.

You can do it using the json package.

Example:

import json
string_containing_json = ".."
data = json.loads(string_containing_json)

Json is just a string arranged in special format. You need to convert it to python objects before using it.

EDIT: I have no idea why the downvote. Judging from the question, this is definitely the issue here. The OP is not converting the json string into dictionary. You can’t iterate over a string, like you do a dictionary.

2👍

You should not dump the data back to JSON in the view. Once you’ve done that, it’s now a string, so it doesn’t have an items method.

You should pass the result of response.json() directly to the template.

1👍

I think, within the view, you need to convert the response like this:

import json

response = requests.request("GET", url, data=payload, headers=headers, params=querystring)        
json_string = json.dumps(response)
return render(request,'searchhome.html',{'dataset':json_string})

And then, I think, you can access the data as

{{ dataset.response_code }}
{{ dataset.response.0 }}

etc

👤HenryM

1👍

Finally I could solve it.
My changed view:

response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
    response = json.loads(response.content) 
    json_string = response["response"]
    return render(request,'searchhome.html',{'dataset':json_string})

My Template

{% for k,v in dataset.items %}
<tr>
<td>
{{k}}:{{v}}</td>
<tr>
{% endfor %}

Solution came with trying all answers posted and just adding .content to json.loads(response)

Leave a comment