Skip to content

Instantly share code, notes, and snippets.

@mostsignificant
Last active December 6, 2022 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mostsignificant/acddc048851d0e751846d24e62afc6d1 to your computer and use it in GitHub Desktop.
Save mostsignificant/acddc048851d0e751846d24e62afc6d1 to your computer and use it in GitHub Desktop.
Converts JSON files to other formats via templates
"""
Converts JSON files to other formats via templates.
"""
import argparse
import json
import os
from jinja2 import Environment, FileSystemLoader
def main():
"""
Parse command line arguments, read JSON from input file, transform via template and write to output file.
"""
parser = argparse.ArgumentParser(
description='Converts JSON files to other formats via templates')
parser.add_argument('input', type=str, help='input file to convert')
parser.add_argument('template', type=str, help='template file for conversion')
parser.add_argument('output', type=str, help='name of the rendered output file')
args = parser.parse_args()
file = open(args.input)
data = json.load(file)
template_dir = os.path.dirname(os.path.abspath(args.template))
environment = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(args.template)
template = environment.get_template(template_file)
content = template.render(data)
with open(args.output, mode='w', encoding='utf-8') as document:
document.write(content)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment