Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f3467cb

Browse files
authored
Merge pull request metafy-social#319 from SiddheshKukade/yml2J
Feature : YAML to JSON Converter
2 parents 1f95b4a + 6dbeddd commit f3467cb

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
### YAML to JSON file converter
2+
Takes YAML data and converts it into JSON by using `json ` and `yml` libraries of `python`.
3+
### To Execute the code
4+
```bash
5+
$ yaml2json.py input_file.yaml output_file.json
6+
```
7+
#### Created by : @SiddheshKukade
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import json
2+
import os
3+
import sys
4+
import yaml
5+
6+
# Checking there is a file name passed
7+
if len(sys.argv) > 1:
8+
# Opening the file
9+
if os.path.exists(sys.argv[1]):
10+
source_file = open(sys.argv[1], "r")
11+
source_content = yaml.safe_load(source_file)
12+
source_file.close()
13+
# Failikng if the file isn't found
14+
else:
15+
print("ERROR: " + sys.argv[1] + " not found")
16+
exit(1)
17+
# No file, no usage
18+
else:
19+
print("Usage: yaml2json.py <source_file.yaml> [target_file.json]")
20+
21+
# Processing the conversion
22+
output = json.dumps(source_content)
23+
24+
# If no target file send to stdout
25+
if len(sys.argv) < 3:
26+
print(output)
27+
# If the target file already exists exit
28+
elif os.path.exists(sys.argv[2]):
29+
print("ERROR: " + sys.argv[2] + " already exists")
30+
exit(1)
31+
# Otherwise write to the specified file
32+
else:
33+
target_file = open(sys.argv[2], "w")
34+
target_file.write(output)
35+
target_file.close()

0 commit comments

Comments
 (0)