Eranki
Eranki

Reputation: 807

Dictionary as string in django template

I have a dictionary in this format:

dict = [{
         "key1": "value1"
         "key2": "value2"
         "key3": "{"name": "", "age": "", "sex": ""}"
       },
     ]

NOTE: key3 is a string holding a dictionary

On the template I can actually pull key1, key2, key3 since they are straight forward. But, key3 is one more dictionary stored in string.

I'm able to do this:

{% for eachObj in dict%}
   { eachObj.key1 }
   { eachObj.key3 } <!-- This prints whole dictionary-->
   { eachObj.key3.name } <!-- This line doesn't work since it is a string -->
{%endfor%}

Is there some way where I can try doing like: JSON.parse(eachObj.key3).name inside that for loop?

Upvotes: 0

Views: 1483

Answers (2)

BeryCZ
BeryCZ

Reputation: 137

Something like this might work then..
You create a custom filter: in templatetags/my_filters.py:

import json

@register.filter
def json_loads(value):
    return json.loads(value)

in your template:

{% load my_filters %}
...
{% with subdata=eachObj.key3|json_loads %}
  {{ subdata.name }}
{% endwith %}

Although I'm not sure your approach is right, you didn't really tell us the reason you have json there

Upvotes: 1

Eranki
Eranki

Reputation: 807

So, I figured out that we can use script tags inside for loop. I've done parsing inside that script tags and printed value using innerHTML.

{%for eachObject in dict%}
   {{eachObject.key1}}
   <span id='key'></span>
   <script>
     var key3="{{eachObject.key3}}"
     // console key3 and check if it has got &quot instead of '. It happend in my case. If so, add the below line:
     key3 = JSON.parse(key3.replace(/&quot;/g,'"'));
     // if your key3 is without &quot, then do JSON.parse(key3) in above line
     document.getElementById("key").innerHTML=key3.name
   </script>
{%endfor%}

Make a note to keep span tags above script tags

Upvotes: 0

Related Questions