Alex.Widmore Alex.Widmore - 1 year ago 65
JSON Question

How do I count the number of times a term has occured in the values of a list of JSON objects?

I am working on a Python code where I need to put a check on the assignment of a value to a key in a JSON object on the basis of user input. My approach is to create a check using the if-statement on the number of times of the occurrence of the specific key value, for that I need to count the number of times that specific key has already been occurred in the object.

I’ve a list of a large number of JSON objects in python in the following format:

[{'name': xyz,
'territory': abc,
'parameter_a': 1,
'parameter_b': 2,
'parameter_c': 3},

Now I want to count the number of times a specific territory (Say ‘abc’) has occurred in the whole list of json objects. Hopefully this makes it clearer.

Answer Source

Could you do

sum((1 for v in json.loads("...") if v.get("territory") == abc))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download