Skip to content

Commit 7102cd2

Browse files
authored
Merge pull request #885 from peleccom/yaml_to_json_argparse
Add option to call yaml_to_json with command line arguments
2 parents 791ee58 + 1504329 commit 7102cd2

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

yaml_to_json/yaml_to_json.py

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
from ruyaml import YAML
2+
import argparse
23
import json
34

45

5-
def get_yaml_data():
6-
yaml_name = input("Enter the yaml file name: ")
6+
def get_yaml_data(yaml_name=None):
7+
if not yaml_name:
8+
yaml_name = input("Enter the yaml file name: ")
79

810
try:
911
with open(yaml_name, "r+") as f:
@@ -14,18 +16,34 @@ def get_yaml_data():
1416
yaml_data = get_yaml_data()
1517

1618

17-
def convert_to_json(yaml_data):
18-
json_name = input("Enter the name of output json file: ")
19+
def convert_to_json(yaml_data, json_name=None, intent=None):
20+
if not json_name:
21+
json_name = input("Enter the name of output json file: ")
1922

2023
try:
2124
with open(json_name, "w+") as o:
22-
o.write(json.dumps(yaml_data))
25+
o.write(json.dumps(yaml_data, indent=intent))
2326
except: # noqa
2427
print("Invalid input enter a valid json file name e.g. example.json")
2528
convert_to_json(yaml_data)
2629

2730

28-
yaml_data = get_yaml_data()
29-
convert_to_json(yaml_data)
31+
def main():
32+
parser = argparse.ArgumentParser(description='Convert YAML file to JSON')
33+
parser.add_argument('--yaml', type=str, help='YAML filename')
34+
parser.add_argument('--json', type=str, help='JSON filename')
35+
parser.add_argument('--intent', type=int, help="intent value for JSON")
36+
args = parser.parse_args()
3037

31-
print("Your yaml file has been converted and saved as json")
38+
yaml_name = args.yaml
39+
json_name = args.json
40+
intent = args.intent
41+
42+
yaml_data = get_yaml_data(yaml_name)
43+
convert_to_json(yaml_data, json_name, intent=intent)
44+
45+
print("Your yaml file has been converted and saved as json")
46+
47+
48+
if __name__ == "__main__":
49+
main()

0 commit comments

Comments
 (0)