【问题标题】:Cannot Get Django Template to Print Formatted JSON无法获取 Django 模板以打印格式化的 JSON
【发布时间】:2017-11-04 20:37:35
【问题描述】:

我正在努力打印来自 Watson 的 NLU API 的格式化 JSON 响应。我正在使用 Python 2.7 和 Django 1.11。我的 views.py 看起来像这样:

def nlu_analysis(request):
    if request.method == 'POST':
        text2send = request.POST.get('text2send')
        natural_language_understanding = NLUV1(
            version='2017-02-27',
            username='####',
            password='####')

    response = natural_language_understanding.analyze(
        text=text2send,
        features=[features.Entities(), ... features.SemanticRoles()])

        parsedData = json.dumps(response, indent=2)
    return render(request, 'analysis.html', {'data': parsedData})

我的 analysis.html 看起来像这样:

  <div class="container text-left">
      <p>{{ data }}</p>
  </div>

所有这些的结果就是数据,JSON 括号打印在一行上,如下所示:

{ "semantic_roles": [ { "action": { "text": "are", "verb": { "text": "be", "tense": "present" }, "normalized ": "be" }, "sentence": "蝙蝠侠和超人正在与坏人作战", ... "keywords": [ { "relevance": 0.931284, "text": "bad guy" }, { "relevance “:0.790756,“文本”:“超人”},{“相关性”:0.752557,“文本”:“蝙蝠侠”}]}

如果我在 for 循环中运行它

<div class="container text-left">
    {% for d in data %}
        <p>{{ d }}</p>
    {% endfor %}
</div>

它只是在每一行的字符上打印

{

"

s

e

米

...

建议 {{ data }} 是一个字符串,仅此而已。

显然我从根本上误解了一些东西。要么是关于 json.dumps(包括 'indent=2')如何工作,要么是如何在我的模板中正确处理它。我怀疑后者,因为通过“数据”传递的信息显然包含所有 JSON 语法。如果我将上面的一行结果放在 JSON 验证器中,它会重新格式化并完美验证。

对于一个完整的新手有什么帮助吗?谢谢。

【问题讨论】:

  • 为什么在将数据传递给模板之前将其 json 转储?没有它,您的 for 循环将完美运行
  • 确实删除了 json.dumps 让我更接近了,但它只让我获得了 JSON 提要的顶层。如何访问 JSON 提要的每个级别?非常感谢阿斯温。
  • 在上面的示例中,当我添加 for 循环时,它会从上面的示例中打印出 'semantic_roles' 和 'keywords'。不是下一个层次。再次感谢。
  • 为此,您只需像使用普通 python 代码访问它们一样嵌套您的 for 循环

标签: python json django


【解决方案1】:

如果您想访问 dict 对象中键的值,您只需要这样做(对于您的示例数据),

{{ response.semantic_roles }}

这里semantic_roles 将被解释为文字字符串,而不使用变量“语义”的值,如果模板上下文中存在的话。而response 是上下文变量的名称。

或者,如果您想使用循环获取字典对象中每个键的值,您可能需要为您的模板创建一个自定义过滤器,

from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key): 
    return dictionary.get(key)

在你的模板中,

{% for key in response %}
{{ response|get_item:key }}
{% endfor %}

当然,请确保在模板标签上调用 load,以便它们对渲染器可见。

这里有一些有用的链接,

【讨论】:

  • Fazil,感谢您提供更多信息和链接。非常有帮助。
  • 感谢支持..!!
【解决方案2】:

你为什么还要解析你的回复。 json.dumps 将 dict 对象转换为字符串。您可以直接将其用作return render(request, 'analysis.html', {'data': response})。

【讨论】:

  • 谢谢尼基尔。这有效,并且上面 html 中的 for 循环确实打印了 json 数据的顶层。现在我需要弄清楚如何通过 html 中的每个部分进行交互以打印每个级别。
  • 您不能直接迭代数据。尝试使用data.semantic_roles。
  • 已接受。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 2020-12-03
相关资源
最近更新 更多