Luke
Luke

Reputation: 467

Populate specific json value to html with django template

I am new to json and not familiar with it.

In my Django view file, I want to pass only certain json values: school, address, each student's name (Andy, Tom, Jack) and id (Andy.id, Tom.id, Jack.id) to the html from Django view. How can I achieve the above case?

my json content is:

{
  "school": "xxx", 
  "address": "xxx", 
  "number": "xxx,
  "students": {
      "Andy": {
        "id": "xxx", 
        "add": "xxx"
      }, 
      "Tom": {
        "id": "xxx", 
        "add": "xxx"
      }, 
      "Jack": {
        "id": "xxx", 
        "add": "xxx"
      }, 
    },  
}

In my view.py, I have got these codes. jresult is the json string and I used json.dumps() to generated JSON, but it will populate all the json data to the html. How can I achieve the above case? Any helps will be appreciated.

def model_form_upload(request):
    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            file = request.FILES['file'].read()
            jresult = execution(file)
            json_string = json.dumps(jresult, indent=4)

            return render(request,
                          'virus/home.html',
                          {'json_string': json_string})

    else:
        form = FileForm()
    return render(request, 'virus/upload.html', {
        'form': form
    })

my home.html template:

<body>
    <pre>{{ json_string|safe }}</pre>
</body>

Upvotes: 0

Views: 2679

Answers (2)

Sachin
Sachin

Reputation: 3674

You can skip using json.dumps and just pass the dict object and then in template access the keys to get the values.

Example:

<!-- template -->

School: {{ json_dict.school }}
Address: {{ json_dict.address }}
<!-- and so on -->

Upvotes: 2

Henry
Henry

Reputation: 15732

A JSON object is very nearly a Python dictionary. With that in mind if you want to filter for just some keys in a dictionary you can use a dictionary comprehension and write something like:

jresult = {k:v for k,v in jresult.items() if k in wanted_keys}

Before you call json.dumps on jresult. Where wanted_keys = ['school', 'address', 'number', 'students']. If you are filtering the 'students' dictionary as well you can do something similar to the above for that specific key.

Upvotes: 1

Related Questions