Nested Json Analyzer-knowledgectyfree
Json Analyzer Task
Nest Json file handle through python
import json
import argparse
import math
getting_values = []
class Json_Script:
def __init__(self, key):
self.key = key
def count_all_keys(self, data, key_count=None, parent_keys=None):
if key_count is None:
key_count = {}
if parent_keys is None:
parent_keys = []
for item in data:
if isinstance(item, dict):
for key, value in item.items():
current_key = key
if parent_keys:
current_key = ".".join(parent_keys + [key])
key_count[current_key] = key_count.get(current_key, 0) + 1
if isinstance(value, list):
self.count_all_keys(value, key_count,
parent_keys + [key])
elif isinstance(value, dict):
self.count_all_keys([value], key_count,
parent_keys + [key])
return key_count
def json_data(self, key_count=None, parent_keys=None):
if key_count is None:
key_count = {}
if parent_keys is None:
parent_keys = []
for item in data:
if isinstance(item, dict):
for key, value in item.items():
current_key = key
if parent_keys:
current_key = ".".join(parent_keys + [key])
key_count[current_key] = key_count.get(current_key, 0) + 1
if isinstance(value, list):
self.count_all_keys(value, key_count,
parent_keys + [key])
elif isinstance(value, dict):
self.count_all_keys([value], key_count,
parent_keys + [key])
count = key_count.get(self.key)
percentage = (count / len(data)) * 100
print(f'{self.key}:{count} [{percentage:.0f}%]')
def extract_values(self, item, parent_keys=None):
if parent_keys is None:
parent_keys = []
if isinstance(item, dict):
for key, value in item.items():
current_key = key
if parent_keys:
current_key = ".".join(parent_keys + [key])
if self.key in current_key:
if isinstance(value, list):
for element in value:
self.extract_values(element, parent_keys + [key])
elif isinstance(value, dict):
self.extract_values(value, parent_keys + [key])
else:
getting_values.append((value))
elif isinstance(value, list):
for element in value:
self.extract_values(element, parent_keys + [key])
elif isinstance(value, dict):
self.extract_values(value, parent_keys + [key])
def json_value(self):
counter_value = {}
for item in data:
self.extract_values(item)
for num in getting_values:
if num in counter_value:
counter_value[num] +=1
else:
counter_value[num] = 1
print("\nValue occurrences:")
if getting_values:
for key, count in counter_value.items():
percentage = (count / len(data)) * 100
print(f"{key}: {count} [{percentage:.0f}%]")
else:
print("No values to count.")
def arguments():
parser = argparse.ArgumentParser(description='Json Script')
parser.add_argument('-f', dest='key', help='For accessing the key values')
parser.add_argument('-g', dest='value', help='For accessing the key values')
args = parser.parse_args()
json_script_instance = Json_Script(args.key if args.key else args.value)
if args.key:
json_script_instance.json_data()
elif args.value:
json_script_instance.json_value()
else:
results = json_script_instance.count_all_keys(data, key_count={})
print("\nKey occurrences:")
for key, count in results.items():
percentage = (count / len(data)) * 100
print(f"{key}: {count} [{math.floor(percentage)}%]")
if __name__ == "__main__":
try:
with open('item.json', 'r') as f:
data = json.load(f)
except FileNotFoundError:
print("Error: JSON file not found.")
exit(1)
except json.JSONDecodeError:
print("Error: Invalid JSON format.")
exit(1)
arguments()
Post a Comment