Luke
Luke

Reputation: 467

Django: how to loop through nested Json object in html

I am new to json, and I have a nested json object called jresult in django view.py. I passed this object to html and I wanna display it in html.

in view.py:

return render(request,'home.html', {'jresult': jresult})

jresult:

{
  "company": "xxx", 
  "address": "xxx", 
  "ceo": "xxx,
  "employee": {
      "Emily": {
        "id": "xxx", 
        "gender": "xxx"
      }, 
      "Tom": {
        "id": "xxx", 
        "gender": "xxx"
      }, 
      "Alex": {
        "id": "xxx", 
        "gender": "xxx"
      }, 
    },  
}

So far I can only loop through the employee's name and display them in the html page: Emily, Tom and Alex by the following html code:

{% for obj in jresult.employee %}
    <p>{{obj}}</p>
{% endfor %}

how can I access the id and gender as well, I have tried

{% for obj in jresult.employee %}
    <p>{{obj}}</p>
    {% for item in jresult.employee.obj.gender %}
        <p>{{item}}</p>
        {% endfor %}
{% endfor %}

but it doesn't work. Any helps will be appreciated.

Upvotes: 0

Views: 3364

Answers (3)

wdfc
wdfc

Reputation: 374

You can do {{ jresult['employee']['Emily'] }} and then use dot notation to print the remaining {{ jresult['employee']['Emily'].gender }} That should print the gender if I am not mistaken. However this is not maintainable as it requires you to know the names of each key before printing.

Django templates should allow you to do something like this, as json should be treated as python dictionary.

{% for employee_key, employee_value in jresult.employee %}
    <p>{{employee_key}}:{{employee_value}}</p>
{% endfor %}

Reference: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#for

Asides from this - I would probably just write a serializer/transformer to change this data into template readable before sending it to the front-end.

Hope this helps!

Upvotes: 1

zubhav
zubhav

Reputation: 1559

JSON is a nested structure so you should be able to access attributes of relative objects using a simple dot notation. You must have the employee field as an array, not an object, if you want to iterate through them like so:

Try this:

{% for obj in jresult.employee %}
   <p>{{obj}}</p>
   <p>{{obj.id}}</p>
   <p>{{obj.gender}}</p>
{% endfor %}

Upvotes: 2

Norman
Norman

Reputation: 485

Take a look at this (similar request) or (if it don't work) you can implement your own filter to transform the json in the desired form

Edit: Basically you can try

{{ jresult['employee'] }}

because as cited in the first link, you have dictionaries in the json

Upvotes: 1

Related Questions