简体   繁体   中英

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

eq: json like:

{
  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)
2: Should give value as count=2 (both name: field is unique)
3: Should give value as count=1 ( one entry as well as unique)

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.

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 .

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.

{
    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:

@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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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