Certainly! Below is a Python script that reads JSON files, iterates through the dictionary, and counts all the keys that have valid (non-None) values.
Script Explanation:
- Reads a JSON file.
- Iterates through all keys in the dictionary.
- Counts keys where the value is not
None.
- Supports nested dictionaries (optional, if you want to count keys in nested structures).
Basic version (flat dictionary):
import json
def count_valid_keys(json_file):
with open(json_file, 'r') as f:
data = json.load(f)
count = 0
for key, value in data.items():
if value is not None:
count += 1
return count
if __name__ == "__main__":
filename = "data.json" # replace with your JSON file path
valid_key_count = count_valid_keys(filename)
print(f"Number of valid keys: {valid_key_count}")
Extended version (handles nested dictionaries):
import json
def count_valid_keys(data):
count = 0
if isinstance(data, dict):
for key, value in data.items():
if value is not None:
count += 1
# If value is a dict, recursively count valid keys inside it
if isinstance(value, dict):
count += count_valid_keys(value)
# If value is a list, check each item if it's a dict
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
count += count_valid_keys(item)
return count
if __name__ == "__main__":
filename = "data.json" # replace with your JSON file path
with open(filename, 'r') as f:
data = json.load(f)
valid_key_count = count_valid_keys(data)
print(f"Number of valid keys (including nested): {valid_key_count}")
How to use:
- Save the script to a
.py file.
- Replace
"data.json" with the path to your JSON file.
- Run the script.
If you want me to help you with reading multiple JSON files from a directory or any other feature, just ask!