python-tutorials/tests/Json2Yaml.py

38 lines
986 B
Python
Raw Normal View History

# Python script to Read file from JSON and convert to YAML
2021-03-12 10:21:18 -05:00
# Author - yucheng.hu@insight.com
2021-03-12 10:21:18 -05:00
import datetime
import json
2021-03-11 10:49:27 -05:00
import ruamel.yaml as yaml
2021-03-12 10:21:18 -05:00
from dateutil.relativedelta import relativedelta
json_filename = 'resources/black_rock_test.json'
yaml_filename = 'resources/black_rock_test.yaml'
2021-03-12 10:21:18 -05:00
ELIGIBLE_FOR_RETIREMENT = 'eligible_for_retirement'
# Get Difference Years
def get_age(data_input):
date_user = datetime.datetime.strptime(data_input, '%m/%d/%Y')
date_current = datetime.datetime.now()
time_difference = relativedelta(date_current, date_user)
return time_difference.years
# Read and process JSON
with open(json_filename) as json_file:
data = json.load(json_file)
2021-03-12 10:21:18 -05:00
data_bod = data['date_of_birth']
2021-03-12 10:21:18 -05:00
if get_age(data_bod) >= 65:
data[ELIGIBLE_FOR_RETIREMENT] = True
else:
data[ELIGIBLE_FOR_RETIREMENT] = False
# Write to YAML
2021-03-11 10:49:27 -05:00
with open(yaml_filename, 'w') as yaml_file:
yaml.dump(data, yaml_file, allow_unicode=True)