Python Script to convert a YAML file to JSON file

Python Script to convert a YAML file to JSON file

Convert a file from yaml to json using Python

Hi there!

In this blog post you'll learn how to convert a YAML file to JSON file using python.

What is YAML?

YAML (a recursive acronym for "YAML Ain't Markup Language") is a human-readable data-serialization language. It is commonly used for configuration files and in applications where data is being stored or transmitted. YAML targets many of the same communications applications as Extensible Markup Language but has a minimal syntax which intentionally differs from SGML.

What is JSON?

JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays. It is a very common data format, with a diverse range of applications, one example being web applications that communicate with a server.

The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only.

Code:

# yaml_json_converter.py
import json
import os
import sys
import yaml

# Checking there is a file name passed
if len(sys.argv) > 1:
    # Checking is the file exists in the given path
    if os.path.exists(sys.argv[1]):
        #Opening the file
        source_file = open(sys.argv[1], "r")
        source_content = yaml.safe_load(source_file)
        source_file.close()
    # Failing 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]")

# Converting the YAML content to JSON
output = json.dumps(source_content)

# If no target file
if len(sys.argv) < 3:
    print("ERROR: Required two arguments")
# Checking is file already exists
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()

You have to pass two arguments while running this script. 1st one is path to source file (YAML) and the 2nd argument is path to target file (JSON).

python yaml_json_converter.py /path/to/source/file.yaml /path/to/target/file.json

Thank you for reading. Please comment your feedback and suggestions.

Did you find this article valuable?

Support Balasundar by becoming a sponsor. Any amount is appreciated!