【发布时间】: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 循环