Home > Software design >  How to fetch list of dictionary json data and show it on html page as table data
How to fetch list of dictionary json data and show it on html page as table data

Time:09-07

I have two columns data.One is "GLI Code" column and another is "Country" column.

I need to set the “GLI Code” data in “GLI Code” column. “Country” data in “Country” column. here is my data in list of dictionary format.

views file:

def tables_data(request):
    dbfs_source_file_path = 'dbfs:/mnt/adls/MPF/Alternate_Currency_Keys_Aug.csv'
    local_file_download_path = './mpf_dataset.csv'
    dbfs_api  = DbfsApi(api_client)
    dbfs_path = DbfsPath(dbfs_source_file_path)
    dbfs_api.get_file(dbfs_path, local_file_download_path, overwrite = True)
    df = pd.read_csv(local_file_download_path).head(5)
    json_records = df.reset_index().to_json(orient ='records')
    data = []
    data = json.loads(json_records)
    return render(request, "home/tables-data.html", {'data':data})

data ouput:

[{'index': 0, 'GLI Code': '15013256_U', 'Country': 'Indonesia', }, 
{'index': 1, 'GLI Code': '20061265_U', 'Country': 'Philippines'}, 
{'index': 2, 'GLI Code': '20063869_U', 'Country': 'Indonesia'}]
 

html file:

 
  <thead> 
  <tr>
    {% for i in data %}
    <th>{{i}}</th>
    {% endfor %}
  </tr>
  </thead>
  <tbody>
  <tr>  
    {% for g in data.GLICode %}
    <td>{{g}}</td>
    {% endfor %} 
  </tr>
  <tr>  
    {% for c in data.Country %}
    <td>{{c}}</td>
    {% endfor %} 
  </tr>
  </tbody>

Above html code not giving me the expected output like below screenshot data.

I want to set the data as below screenshot format.

enter image description here

CodePudding user response:

I think it will be better to use ajax request Instead of it please Visit: https://www.google.com/amp/s/www.geeksforgeeks.org/handling-ajax-request-in-django/amp/

But the main problem with your code is that you are trying to get key in HTML which in is not quite correct you can see an example Visit: https://www.appsloveworld.com/django/100/431/how-to-display-json-items-in-django-templates

CodePudding user response:

Doing something like this would work, but! you must remove the Space from 'GLI Code' in data.. Using Dictionary keys with spaces in Templates seems like a giant headache (extra custom template tags stuff) - can be done, do not recommend

<table> 
  <thead>
    <tr>
      <th></th>
      <th>GLI Code</th>
      <th>Country</th>
    </tr>
  </thead>
  <tbody>
    {% for i in data %}
      <tr>
        <th>{{i.index}}</th>
        <th>{{i.GLICode}}</th>
        <th>{{i.Country}}</th>
      </tr>
    {% endfor %}
  </tbody>
</table>
  • Related