I have a folder with many json files like below
sample1.json:
[{
"TimeField": "UTC",
"Subject": "",
"Severity": "Medium",
},
{
"TimeField": "MDT",
"Subject": "",
"Severity": "Medium",
}]
sample2.json:
[{
"TimeField": "UTC",
"Subject": "",
"Severity": "low",
"Comment" : ""
},
{
"TimeField": "MDT",
"Subject": "",
"Severity": "low",
"Comment" : ""
}]
My code:
def get_parameters(obj):
timefield = obj['TimeField']
subject = obj['Subject']
severity = obj['Severity']
comment = obj['Comment']
return(timefield ,subject ,severity ,comment )
try:
path = "/opt/AAA/aaa"
for files in os.listdir(path):
try:
if files.endswith('.json'):
json_path = os.path.join(path, files)
with open(json_path, "r") as json_file:
json_index = json.load(json_file)
for obj in json_index:
parameters = get_parameters(obj)
except Exception as ex:
DEBUGLOG_OBJ.critical("Exception Line no: {0} : {1} while executing ".format(sys.exc_info()[-1].tb_lineno, ex))
Getting exception due to Comment not in sample1.json:
CRITICAL - Exception Line no: : 'Comments'
How to parse json files with variable number of key value pair