去掉json对象最后一个对象的逗号

AHB*_*AHB 0 python jinja2 python-3.x

我使用 jinja2 创建了一个模板,它会按预期生成输出。

但是,我试图从生成的 JSON 的最后一个对象中删除逗号。我尝试使用 {% if loop.last %} 来去掉最后一个对象的逗号。

但是,我无法得到正确的输出。

{% if loop.last %}
    {
    "met" : {{j}},
    "uri" : "{{i}}"
     }
{% endif %}
Run Code Online (Sandbox Code Playgroud)

下面是代码和输出

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)
Run Code Online (Sandbox Code Playgroud)

输出:

{% if loop.last %}
    {
    "met" : {{j}},
    "uri" : "{{i}}"
     }
{% endif %}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

不要使用 Jinja2 手动生成 JSON。您不能希望在所有情况下都能生成保存且有效的 JSON。

在较大模板中嵌入 JSON 时,使用tojson内置过滤器生成 JSON。它不会包含尾随逗号。

我将传递带有两个列表的乘积的现成字典:

uri_per_metric = [{'met': m, 'uri': u} for u in uri for m in metric_value]
Run Code Online (Sandbox Code Playgroud)

在模板中只需使用

{{ uri_per_metric|tojson(indent=4) }}
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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>
Run Code Online (Sandbox Code Playgroud)

当然,如果您正在生成响应(仅从Web 端点application/json返回JSON 数据)并且这不是较大模板的一部分,那么根本使用模板将不是一个好主意。在这种情况下,请使用您的 Web 框架可能拥有的专用 JSON 支持,例如Flask 的响应工厂方法,或直接生成输出。jsonify()json.dumps()