Home > Net >  Parse all valid datetime strings in json recursively
Parse all valid datetime strings in json recursively

Time:06-06

I have a json blob of the following format. Is there a way to identify all strings which match the format

%Y-%m-%dT%H:%M:%S

And convert them to datettime strings

{
    "data":[
        {
            "name":"Testing",
            "dob":"2001-01-01T01:00:30"
        },
        {
            "name":"Testing2",
            "dob":"2001-01-01T01:00:30",
            "licence_info":{
                "issue_date":"2020-01-01T01:00:30"
            }
        }
    ]
}

CodePudding user response:

The easiest way to do this is to parse each value and attempt to convert it to a datetime. You could do something like this:

from datetime import datetime

def convert_dates(value):
    if isinstance(value, dict):
        return { k : convert_dates(v) for k, v in value.items() }
    elif isinstance(value, list):
        return [ convert_dates(v) for v in value ]
    else:
        try:
            dt = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
            return dt
        except ValueError:
            return value

jstr = '''
{
    "data":[
        {
            "name":"Testing",
            "dob":"2001-01-01T01:00:30"
        },
        {
            "name":"Testing2",
            "dob":"2001-01-01T01:00:30",
            "licence_info":{
                "issue_date":"2020-01-01T01:00:30"
            }
        }
    ]
}
'''
d = json.loads(jstr)
convert_dates(d)

Output:

{
 'data': [
    {'name': 'Testing',
     'dob': datetime.datetime(2001, 1, 1, 1, 0, 30)
    },
    {'name': 'Testing2',
     'dob': datetime.datetime(2001, 1, 1, 1, 0, 30),
     'licence_info': {'issue_date': datetime.datetime(2020, 1, 1, 1, 0, 30)}
    }
  ]
}
  • Related