Created
December 19, 2017 13:18
-
-
Save j18e/2edcbe60deccb7fc7cfcdda78e813364 to your computer and use it in GitHub Desktop.
Yaml Parser for Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Yaml Parser | |
Usage: yaml_parser.py [-f FILE] [KEYS] | |
Parses yaml file using provided keys in 'key.otherkey.anotherkey' format | |
If result is a datastructure, response comes in JSON | |
Arguments: | |
FILE file containing yaml formatted data. Alternatively, use stdin | |
KEYS period separated list of keys to parse through | |
Options: | |
-h | |
-f FILE | |
Example: yaml-parser.py parameters/blue.yml TemplateParameters.server1.field | |
""" | |
from docopt import docopt | |
import sys | |
import yaml | |
import json | |
if __name__ == '__main__': | |
args = docopt(__doc__) | |
def dict_or_list(string): | |
try: | |
num = int(string) | |
except ValueError: | |
return string | |
return num | |
def parse_data(results, keys): | |
for i in keys: | |
results = results[dict_or_list(i)] | |
if type(results) is dict or type(results) is list: | |
results = json.dumps(results) | |
return results | |
if args['-f']: | |
data = yaml.load(open(args['-f'])) | |
else: | |
data = yaml.load(sys.stdin) | |
keys = [] | |
if args['KEYS']: | |
keys = args['KEYS'].split('.') | |
print(parse_data(data, keys)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment