Merge pull request #319 from SiddheshKukade/yml2J

Feature : YAML to JSON Converter
This commit is contained in:
Advaita Saha 2022-10-10 20:48:34 +05:30 committed by GitHub
commit f3467cbe7e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,7 @@
### YAML to JSON file converter
Takes YAML data and converts it into JSON by using `json ` and `yml` libraries of `python`.
### To Execute the code
```bash
$ yaml2json.py input_file.yaml output_file.json
```
#### Created by : @SiddheshKukade

View File

@ -0,0 +1,35 @@
import json
import os
import sys
import yaml
# Checking there is a file name passed
if len(sys.argv) > 1:
# Opening the file
if os.path.exists(sys.argv[1]):
source_file = open(sys.argv[1], "r")
source_content = yaml.safe_load(source_file)
source_file.close()
# Failikng if the file isn't found
else:
print("ERROR: " + sys.argv[1] + " not found")
exit(1)
# No file, no usage
else:
print("Usage: yaml2json.py <source_file.yaml> [target_file.json]")
# Processing the conversion
output = json.dumps(source_content)
# If no target file send to stdout
if len(sys.argv) < 3:
print(output)
# If the target file already exists exit
elif os.path.exists(sys.argv[2]):
print("ERROR: " + sys.argv[2] + " already exists")
exit(1)
# Otherwise write to the specified file
else:
target_file = open(sys.argv[2], "w")
target_file.write(output)
target_file.close()