Last active
January 7, 2019 20:33
-
-
Save dpetzold/16e5e3fe482542299cb9b6866dc476f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
""" | |
A tool to convert camelcase field names in JSON to snake case. Helps with converting | |
AWS dumps to terraform HCL. For example: | |
``` | |
$ aws cloudfront get-distribution --id <id> --query Distribution > dist.json | |
$ python3 terraform_case.py dist.json dist.tf | |
``` | |
""" | |
import argparse | |
import re | |
import json | |
def camel2snake(name): | |
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) | |
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | |
def convert_obj(obj): | |
out = {} | |
if isinstance(obj, str): | |
return obj | |
for k, v in obj.items(): | |
if isinstance(v, dict): | |
out[camel2snake(k)] = convert_obj(v) | |
elif isinstance(v, list): | |
out[camel2snake(k)] = [ | |
convert_obj(i) for i in v | |
] | |
else: | |
out[camel2snake(k)] = v | |
return out | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('file', type=argparse.FileType('r')) | |
parser.add_argument('dest', type=argparse.FileType('w')) | |
args = parser.parse_args() | |
with args.file as fh: | |
args.dest.write( | |
json.dumps( | |
convert_obj( | |
json.load(fh) | |
) | |
) | |
) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment