← Runnable Projects

阅读中文版本

YAML to JSON Converter in Python

A Python script that loads a YAML file with PyYAML and prints the equivalent JSON, preserving order and reporting parse errors clearly.

beginnerpythonunverified

Project

python-yaml-to-json

Entry point: yaml_to_json.py

Install

python -m pip install pyyaml

Run

python yaml_to_json.py config.yaml

Test

python -m unittest -v test_yaml_to_json.py

Expected output

Prints the YAML document as indented JSON, or exits non-zero with the YAML line and column on a parse error.

Dependencies

  • python >=3.10
  • pyyaml >=6.0

What it does

Uses the safe loader so no arbitrary Python objects are constructed from the document, then serializes to JSON with indentation. Errors carry the problem mark and exit non-zero for scripting.

import json
import sys
import yaml


def load(path: str):
    with open(path, "r", encoding="utf-8") as handle:
        return yaml.safe_load(handle)


def main(argv):
    if len(argv) != 2:
        print("usage: yaml_to_json.py <file.yaml>", file=sys.stderr)
        return 2
    try:
        doc = load(argv[1])
    except yaml.YAMLError as exc:
        print(f"yaml error: {exc}", file=sys.stderr)
        return 1
    print(json.dumps(doc, indent=2, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))

Run and verify

python yaml_to_json.py config.yaml

Run the test command to check the implementation: python -m unittest -v test_yaml_to_json.py.

Expected Output

For a YAML file containing name: demo and a nested server.port: 8080, the output is JSON:

{
  "name": "demo",
  "server": {
    "port": 8080
  }
}

Limitations

Uses the safe loader, so custom YAML tags and language-specific types are rejected rather than converted; that is deliberate to avoid executing arbitrary constructors.