迭代json.dumps()的模板内部,模板中的预格式化标签

时间:2019-06-13 11:15:10

标签: python json django parsing django-templates

我终于成功地列出了通过模板呈现的“树”嵌套JSON响应。但是要付出代价。我无法遍历模板中的ID和值(传递给模板的上下文)。
至于非嵌套的JSON响应,我可以在模板中进行迭代并处理想要的任何ID和值。但是当我尝试使用嵌套的JSON响应(JSON内的JSON)来执行此操作时,无能为力。

非嵌套JSON 场景代码和效果:
views.py

def about(request, host_id):
    hostname = Host.objects.get(pk=(host_id))
    response = requests.get(
        'https://{}:1769/api/v1/about'.format(hostname),
        verify='cert/cacerts.pem',
        headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxx'},
    ).json()
    context = {'response': response, 'hostname': hostname}
    return render(request, 'itpassed/json.html',context)

json.html

[...]
{% if response %}
    {% for id, value in response.items %}
        <p><b>{{ id }}:</b>
        <br>
        {{ value }}</p>
    {% endfor %}
{% else %}
    <p>No IDs are available.</p>
{% endif %}
[...]

在浏览器中的效果:

版本:
3.4

级别:

系统:
Unix

服务器时间:
1560423771000

server_utc:
2


嵌套JSON 方案代码和效果:
views.py

def transfers(request, host_id):
    hostname = Host.objects.get(pk=(host_id))
    response = requests.get(
        'https://{}:1769//api/v1/transfers?fields=PART%2CDIRECT%2CTYPE[...]&limit=100'.format(hostname),
        verify='cert/cacerts.pem',
        headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxx'},
    ).json()
    response = json.dumps(response, indent=3)
    context = {'response': response, 'hostname': hostname}
    return render(request, 'itpassed/json_nest.html', context)

json_nest.html

[...]
{% if response %}
<pre>{{ response }}</pre>
{% else %}
    <p>No IDs are available.</p>
{% endif %}
[...]

在浏览器中的效果:

{
   "transfers": [
      {
         "part": "HOSTNAME_SSL",
         "direct": "SEND",
         "type": "MESSAGE",
         "compatstate": "T",
         "state": "T",
         "idf": "NOW",
         "idt": "F1112091",
         "idtu": "A000000H",
         "msg": "test",
         "requser": "usr",
      },
      {
         "part": "HOSTNAME2_SSL",
         "direct": "SEND",
         "type": "MESSAGE",
         "compatstate": "T",
         "state": "T",
         "idf": "TEST",
         "idt": "F1110560",
         "idtu": "A000000G",
         "msg": "test",
         "requser": "usr",
      }
   ],
   "numberOfSelectedRecords": 2,
   "numberOfUsedRecords": 2,
   "numberOfRecords": 10000,
   "offset": 0
}

是否有可能像在非嵌套方案中一样在嵌套方案中管理JSON响应?我的意思是“粗体” ID(转移)或ID内的ID(部分,直接等)
我尝试了多种传递JSON和呈现JSON的方法,但这是可行的方法,并且与我的期望最接近。

0 个答案:

没有答案