Skip to main content

Is there a JSON function that we can get a count for certain field/group them by distinct values.

  • August 14, 2023
  • 4 replies
  • 13 views

Forum|alt.badge.img+4

Is there a JSON function so that we can get a count for certain field and group them by distinct values. So the JSON result have the following response:
{
name: John,
name: Kevin,
name: John,
name: Sara,
name: John
} The output should be -
John(3), Kevin,(1),Sara(1)

4 replies

Forum|alt.badge.img+1
  • New Member
  • August 14, 2023

Hey @krunalm
The only way I can think of is using TemplateEngine to iterate the json results and format it to your desired format:

View files in slack


Forum|alt.badge.img+1
  • New Member
  • August 14, 2023

This will output:

View files in slack


Forum|alt.badge.img+1
  • New Member
  • August 14, 2023

And here's the json I used and jinja template:
Json:
{
"results": [
{"name": "John"},
{"name": "Kevin"},
{"name": "John"},
{"name": "Sara"},
{"name": "John"},
{"name": "Kevin"}
]
} Jinja Template:
{% set names = [] %}
{% for item in input_json.results if item.name not in names %}
{% do names.append(item.name) %}
{% endfor %}
{% for name in names %}
{{ name }} ({{ input_json.results | selectattr("name", "equalto", name) | list | count }}){% if (loop.index) != names|length -%},{% endif -%}
{%- endfor -%}


Forum|alt.badge.img+4
  • Author
  • New Member
  • August 14, 2023

Thanks so much for your help! I'll test this out and see if that works.