AHB
AHB

Reputation: 129

Remove the comma from the last object of json object

I have created a template using jinja2 Which generates the output as expected.

However, I'm trying to remove the comma from the last object of the generated JSON. I tried using {% if loop.last %} to get rid of the comma for the last object.

But, I couldn't get the correct output.

{% if loop.last %}
    {
    "met" : {{j}},
    "uri" : "{{i}}"
     }
{% endif %}

Below is the code and output

from jinja2 import Template

uri = ["example1.com","example2.com"]
metric_value = [1024, 2048]

template = Template('''\
[
{%- for i in uri -%}
    {%- for j in met %}
    {
        "met" : {{j}},
        "uri" : "{{i}}"
    },
    {%- endfor -%}
{%- endfor %}
]
''')

payload = template.render(uri=uri, met=metric_value)                                 
print(payload)

output:

[
    {
        "met" : 1024,
        "uri" : "example1.com"
    },
    {
        "met" : 2048,
        "uri" : "example1.com"
    },
    {
        "met" : 1024,
        "uri" : "example2.com"
    },
    {
        "met" : 2048,
        "uri" : "example2.com"
    },
]

Upvotes: 0

Views: 3327

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122262

Don't manually generate JSON with Jinja2. You can't hope to generate save and valid JSON in all circumstances.

When embedding JSON in a larger template, use the tojson built-in filter to generate JSON. It will not include a trailing comma.

I'd pass in ready-made dictionaries with the product of the two lists:

uri_per_metric = [{'met': m, 'uri': u} for u in uri for m in metric_value]

and in the template just use

{{ uri_per_metric|tojson(indent=4) }}

Demo:

>>> from jinja2 import Template
>>> uri = ["example1.com", "example2.com"]
>>> metric_value = [1024, 2048]
>>> uri_per_metric = [{'met': m, 'uri': u} for u in uri for m in metric_value]
>>> template = Template('''\
... <script type="text/javascript">
... data = {{ uri_per_metric|tojson(indent=4) }};
... </script>
... ''')
>>> payload = template.render(uri_per_metric=uri_per_metric)
>>> print(payload)
<script type="text/javascript">
data = [
    {
        "met": 1024,
        "uri": "example1.com"
    },
    {
        "met": 2048,
        "uri": "example1.com"
    },
    {
        "met": 1024,
        "uri": "example2.com"
    },
    {
        "met": 2048,
        "uri": "example2.com"
    }
];
</script>

Of course, if you are producing a application/json response (returning only JSON data from a web endpoint) and this is not part of a larger template, then using templating at all would be a bad idea. In that case use the dedicated JSON support your web framework might have, such as Flask's jsonify() response factory method, or produce the output with json.dumps() directly.

Upvotes: 6

Related Questions