Skip to content

Instantly share code, notes, and snippets.

@antoooks
Created October 3, 2021 04:52
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 antoooks/957480b78bb9c745ebc354cd22801acf to your computer and use it in GitHub Desktop.
Save antoooks/957480b78bb9c745ebc354cd22801acf to your computer and use it in GitHub Desktop.
Generate JSON files from YAML files given directory name
# Run using `python3 main.py`
# Input: relative or absolute path of a dir with YAML files inside
# Output: JSON files inside the provided directory
import os
import yaml
import json
directory_path = os.path.abspath(input("Please enter your directory relative path: "))
directory_list = os.listdir(directory_path)
if not any(".yaml" in string for string in directory_list):
print("No YAML file(s) found.")
exit(1)
for files in directory_list:
if files.endswith(".yaml"):
file_path = directory_path + "/" + files
with open(file_path, "r") as stream:
try:
yaml_file = yaml.safe_load(stream)
json_file_name = os.path.splitext(files)[0] + ".json"
json_file_path = directory_path + "/" + json_file_name
print("Processing " + json_file_name + " ...")
json_file = open(json_file_path, "w")
json_file.write(json.dumps(yaml_file))
json_file.close()
except yaml.YAMLError as e:
print(e)
exit(1)
else:
continue
print("Done !")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment