I'm struggling with printing a formatted JSON response from Watson's NLU API. I'm using Python 2.7 and Django 1.11. My views.py looks like this:
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})
My analysis.html looks like this:
<div class="container text-left">
<p>{{ data }}</p>
</div>
The result of all of this is the data, with JSON brackets being printed on one line like this:
{ "semantic_roles": [ { "action": { "text": "are", "verb": { "text": "be", "tense": "present" }, "normalized": "be" }, "sentence": "Batman and Superman are fighting the bad guys", ... "keywords": [ { "relevance": 0.931284, "text": "bad guys" }, { "relevance": 0.790756, "text": "Superman" }, { "relevance": 0.752557, "text": "Batman" } ] }
If I run this within a for loop
<div class="container text-left">
{% for d in data %}
<p>{{ d }}</p>
{% endfor %}
</div>
it simply prints on character on each line
{
"
s
e
m
...
suggesting that {{ data }} is a string, nothing more.
Clearly I am fundamentally misunderstanding something. Either it is something with respect to how json.dumps (including 'indent=2') works or how to deal with it properly in my template. I suspect the later as the information being passed via 'data' clearly contains all of the JSON syntax. If I place the one line result above result in a JSON validator it reformats and validates perfectly.
Any help for a complete rookie out there? Thanks.