Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django- Json data in template

I am accessing an API and get JSON data. I can see that JSON is generated. However I am not able to show it in template.

Below is the sample Json data.

{  
   "response_code":1,
   "response":{  
      "a":"01/07/2017",
      "b":"12",
      "c":"23",
      "d":"34",
      "e":"45",
      "f":"56",

   },
   "error_code":null,
   "error_message":null
}

I passed this data in view to template as dataset. View as asked in comment.

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

What I tried in template.

{% for key, value in dataset.items %}
{{key}}: {{value}}
{% endfor %}

Another try

{% for d in dataset %}
{% for key, value in d.response.items %}
{{key}} {{value}}
{% endfor %}
{% endfor %}

Template is not showing any error or any response. What I am doing wrong here?

like image 328
Sapna Sharma Avatar asked Sep 03 '25 01:09

Sapna Sharma


2 Answers

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.

like image 91
Sidhin S Thomas Avatar answered Sep 07 '25 01:09

Sidhin S Thomas


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

like image 34
HenryM Avatar answered Sep 07 '25 01:09

HenryM