Django - How to process JSON response from TwelveData API in Template?

231 Views Asked by At

In a hobby project, I am using TwelveData API to receive Time Series Data. I am using JSON format response and able to check each data (example: open, close, high, and etc.) from Python side, but the problem arises when I try to show the data in a Django Template page using a for-loop. The JSON response is similar to below image:

enter image description here

When I write the following for loop in the template:

{%for r in result %}
    {{r}}
{%endfor %}

It prints GOOGL, AAPL, AMZN, and TSLA <-- which is pretty good. Now when I write another for loop like:

{%for r in result %}
    {%for k in result.r %}
        {{k}}
    {%endfor %}
{%endfor %}

It prints nothing except a blank page. So I rewrite the main for-loop as follows:

{%for r,v in result %}
    {{v}}
{%endfor %}

It prints ValueError: Need 2 values to unpack in for loop; got 5.

Can anyone help me identify how to run the loop accurately so that I can get/print (maybe inside a table tag) the JSON response data as follows: open, close, high, and etc.

  • Thanks
2

There are 2 best solutions below

5
Anton Pomieshchenko On

I think you should use items for result

{% for r,v in result.items %}
    {{r}} - {{ v }}
{% endfor %}

Also you need to convert string to json

import json

# somewhere before you pass result to template
result = json.loads(result)
0
Minh Vương Phan On

Using result.r will make Django look for property, not value of the key. That is why its print nothing using your second code. You could see Anton Pomieshchenko's anwser to enumerate a dict or write a custom template filter if you want to get the value of a specific key:

from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

usage:

{% for r in result %}
    {{ result|get_item:r }}
{% endfor %}