简体   繁体   English

如何使用 Jinja2 计算 Json 中唯一值的数量?

[英]How can i count the no of unique values in a Json using Jinja2?

eq: json like: eq:json 喜欢:

{
  1: [
    {id: 1, name = "sam"},
    {id: 1, name = "sam"},
  ],
  2: [
    {id: 1, name = "p"},
    {id: 2, name = "e"},
  ],
  3: [
    {id: 2, name = "alice"}
  ],
  4: [
    {id: 3, name = "sam"}
  ]
}

So, desired output:因此,所需的输出:

1: Should give value as count=1 (the name: value is not unique) 1:应将值设为 count=1(名称:值不是唯一的)
2: Should give value as count=2 (both name: field is unique) 2:应将值设为 count=2(两个名称:字段是唯一的)
3: Should give value as count=1 ( one entry as well as unique) 3:应该给值计数=1(一个条目以及唯一的)

so on...很快...

So code written:所以写的代码:

{% for row in groups %} 
{% set count = namespace(value=0) %} 
<tr> {% for items in groups[row[0]] %} 
{% if 'name' in items %} 
{% set count.value = count.value + 1 %}
{% endif %}
{% endfor %}
<td>{{count.value}}</td>
</tr>

This code is only counting the no of entries.此代码仅计算条目数。 not the unique value count.不是唯一值计数。

Generally speaking you should probably put such logic into your Python code, as noted by commenter yedpodtrzitko.一般来说,正如评论者 yedpodtrzitko 所指出的那样,您可能应该将此类逻辑放入您的 Python 代码中。

If you are using jinja2 through Flask, the most convenient way to do this is likely to define a context processor, as outlined in the documentation here .如果您是通过烧瓶中使用Jinja2的,最便捷的方式做,这是有可能定义一个上下文处理器,如文档中列出这里

In my example I assume that you are working on a Python dictionary, even though your question mentions a JSON, which might indicate some confusion as to the data that jinja can access.在我的示例中,我假设您正在使用 Python 字典,即使您的问题提到了 JSON,这可能表明 jinja 可以访问的数据有些混乱。

{
    1: [
        {'id': 1, 'name': 'sam'},
        {'id': 1, 'name': 'sam'},
    ],
    2: [
        {'id': 1, 'name': 'p'},
        {'id': 2, 'name': 'e'},
    ],
    3: [
        {'id': 2, 'name': 'alice'}
    ],
    4: [
        {'id': 3, 'name': 'sam'}
    ]
}

Assuming that the IDs in your example uniquely identify the individual entries in the list an efficient way to do this is to use the fact that a set only includes unique values, other than a list which can hold multiple identical integers:假设您的示例中的 ID 唯一标识列表中的各个条目,一种有效的方法是利用这样一个事实,即集合仅包含唯一值,而不是可以包含多个相同整数的列表:

@app.context_processor
def utility_processor():
    def count_unique_dicts(input_list):
        unique_ids = set([entry['id'] for entry in input_list])
        return len(unique_ids)

    return dict(count_unique_dicts)

You can then use this context processor in your template as follows:然后,您可以在模板中使用此上下文处理器,如下所示:

{% for row in groups %}
Count: {{count_unique_dicts(row)}}
{% endear %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM