Tony Hansen | aeb3db3 | 2017-09-18 14:29:30 +0000 | [diff] [blame^] | 1 | #!/usr/bin/env python3 |
| 2 | # -*- indent-tabs-mode: nil -*- vi: set expandtab: |
| 3 | |
| 4 | """ |
| 5 | NAME |
| 6 | yamltojson - convert a yaml file to a json file |
| 7 | |
| 8 | SYNOPSIS |
| 9 | yamltojson file.yaml ... |
| 10 | |
| 11 | DESCRIPTION |
| 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 | |
| 16 | import sys, re, yaml |
| 17 | try: |
| 18 | import simplejson as json |
| 19 | except: |
| 20 | import json |
| 21 | |
| 22 | def die(msg): |
| 23 | """ generate a FATAL message to stdout and exit """ |
| 24 | print("%s:FATAL:%s" % (date(), msg)) |
| 25 | sys.exit(2) |
| 26 | |
| 27 | for 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) |