Skip to main content
 首页 » 编程设计

python之在 Django 中将 JSON 显示为表

2024年10月01日29lhb25

我有以下 JSON 文件

[{ 
"ID": 1, 
"Name": "John Smith", 
"IDNumber": "7606015012088" 
}, 
{ 
"ID": 2, 
"Name": "Molly Malone", 
"IDNumber": "8606125033087" 
}] 

我想以表格格式显示它。我已经使用 json.load(filename) 解析了 json 文件

我试过类似的东西:

View .py

import json 
 
from django.shortcuts import render 
from django.http import HttpResponse, JsonResponse 
from django.template.loader import render_to_string 
 
# Create your views here. 
 
with open('/home/kunal.jamdade/Desktop/PyCharmProjects/demo.json') as d: 
    data = json.load(d) 
 
 
def load_json_table_format(request): 
    print(data) 
    html = render_to_string() 
    return HttpResponse({'d':data}, 'demoApp/demo.html', content_type="application/html") 
    #return JsonResponse(data, safe=False,content_type="application/html") 
    #return render(request, 'demoApp/demo.html', {'d': data}, content_type="application/html") 

演示.html

<body> 
{% if data %} 
<table> 
    {% for k in d %} 
    {% for item_1, item_2 in k.items %} 
    <tr> 
        <td>{{ item_1 }}</td> 
        <td>{{ item_2 }}</td> 
    </tr> 
    {% endfor %} 
    {% endfor %} 
</table> 
{% endif %} 
</body> 

但它没有打印任何东西?

请您参考如下方法:

我看到的唯一问题是您使用了 {% if data %}。而是使用 {% if d %}。当您将 data 作为 d 发送时。