One of the reasons I like to use JSONFields in my Django applications is that I can store an entire REST API request body and response body as a JSON object to be accessed like a dictionary later. I would even access it this way in templates to dynamically display data. It’s magical.
However, I’ve recently imported a bunch of data and the JSONField validation managed to import the API responses as strings instead of valid JSON. Why? I don’t know for sure yet but it bothers me.
So I wrote a quick template tag that will process the JSON string and return a dictionary-like object which allows me to parse data the same as before. Beautiful.
# custom_tags.py
import json
from django import template
register = template.Library()
@register.filter(name='jsonify')
def jsonify(data):
if isinstance(data, dict):
return data
else:
return json.loads(data)
This only requires me to change my template slightly. Here’s what it looked like prior to Django 2.2:
{% for call in api_calls %}
{% if call.response.specificResponseKey %}
<p>{{ call.response.specificResponseKey.anotherSpecificKey }}</p>
{% endif %}
{% endfor %}
And after applying my new template tag:
{% load custom_tags %}
{% for call in api_calls %}
{% with call.response|jsonify as response %}
{% if response.specificResponseKey %}
<p>{{ response.specificResponseKey.anotherSpecificKey }}</p>
{% endif %}
{% endwith %}
{% endfor %}
While I could find out why the JSONField didn’t translate the whole API response, which was in valid JSON format, I think this post was more about solving a specific problem in a forward thinking way. Should data be imported improperly again in a way I can’t anticipate, the templatetag will have my back.