How to Count Occurrences of a Field in a JSON Using Python?

Estimated read time 1 min read

To count occurrences of a field in a JSON using Python, you can iterate through the JSON data and use a counter to keep track of the occurrences of the desired field. Here’s an example:

import json

# Load JSON data
with open('example.json') as json_file:
    data = json.load(json_file)

# Define the field to count
field_name = 'field_name'

# Initialize counter
count = 0

# Iterate through JSON data and count occurrences of the field
for item in data:
    if field_name in item:
        count += 1

print(f"Field '{field_name}' occurs {count} times in the JSON data.")

In this example, the json.load() function is used to load the JSON data from a file named “example.json”. The field_name variable is set to the name of the field that you want to count occurrences for. The count variable is initialized to 0, and then a loop iterates through each item in the JSON data. If the field name is found in an item, the count is incremented by 1. Finally, the count is printed to display the total number of occurrences of the field in the JSON data.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply