1

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

1 Answer 1

2

The objects in your json_index are standard dicts, so you can just use dict.get for all optional keys.

def get_parameters(obj):
    
     timefield = obj['TimeField']
     subject = obj['Subject']
     severity = obj['Severity']
     comment = obj.get('Comment')
     return(timefield ,subject ,severity ,comment )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.