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

Viewed 46

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

2 Answers

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>

—-

Edit

To rename the column I’d do something like:

for i in data:
    i[‘GLICode’] = i.pop(‘GLI Code’)

I wrote this on Mobile so there might be something wrong, but the pieces are all there.

Related