使用Django模板将JSON填充到HTML中

3 投票
2 回答
3709 浏览
提问于 2025-04-17 12:49

为了更好地调试我的API,我想创建一个调试页面,逐行显示响应的JSON对象的所有细节。我觉得可以通过代码或者Django模板来实现。最简单的方法是什么呢?

https://developers.facebook.com/tools/explorer/?method=GET 例如,Facebook的探索工具就像这样列出了响应JSON对象的细节。

{
  "id": "xxx", 
  "name": "xxx", 
  "first_name": "xxx", 
  "last_name": "xxx", 
  "link": "xxx", 
  "username": "xxx", 
  "hometown": {
    "id": "xxx", 
    "name": "xxx"
  }, 
  "location": {
    "id": "xxx", 
    "name": "xxx"
  }, 
  "bio": "Drink Coffee in Whitehorse", 

  "work": [
    {
      "employer": {
        "id": "xxx", 
        "name": "xxx"
      }, 
      "location": {
        "id": "xxx", 
        "name": "xxx"
      }, 
      "position": {
        "id": "xxx", 
        "name": "xxx"
      }, 
      "start_date": "2009-01", 
      "end_date": "0000-00"
    }, 
}

2 个回答

2

我建议你在HTML中使用 <pre></pre> 标签,这样你的json看起来会更美观。

import json
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render
from .models import Scan

    @staff_member_required
    def info(request):
        my_info = Scan.scan()
        return render(request, 'info.html', {'info': json.dumps(my_info, indent=4)})

HTML:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <pre>{{ info|safe }}</pre>
    </body>
</html>
9

你只需要用 json.dumps() 这个函数,并且给它一个叫 indent 的参数,这个参数的值就是你想要的缩进空格数,这样生成的 JSON 就会格式化得更好看。

比如:

json.dumps(spam_and_eggs, indent=4)

撰写回答