blob: 0dc85fcbaf83ffa1fd1172a64e23ed685915c79d [file] [log] [blame]
Tony Hansenaeb3db32017-09-18 14:29:30 +00001#!/usr/bin/env python3
2# -*- indent-tabs-mode: nil -*- vi: set expandtab:
3
4"""
5NAME
6 yamltojson - convert a yaml file to a json file
7
8SYNOPSIS
9 yamltojson file.yaml ...
10
11DESCRIPTION
12 Read in a yaml file (whose name must end with ".yaml") and create cor‐
13 responding json files, whose names will end with ".json".
14"""
15
16import sys, re, yaml
17try:
18 import simplejson as json
19except:
20 import json
21
22def die(msg):
23 """ generate a FATAL message to stdout and exit """
24 print("%s:FATAL:%s" % (date(), msg))
25 sys.exit(2)
26
27for fname in sys.argv[1:]:
28 if fname.endswith(".yaml"):
29 y = None
30 with open(fname, "r") as fd:
31 try:
32 contents = fd.read()
33 contents = re.sub("^\t+", " ", contents, flags=re.M)
34 y = yaml.safe_load(contents)
35 except:
36 die("Invalid yaml in '%s'" % fname)
37 jsonfname = fname[:-5] + ".json"
38 with open(jsonfname, "w") as fd:
39 json.dump(y, fd, indent=4, sort_keys=True)