1
0
mirror of https://github.com/kellyjonbrazil/jc.git synced 2025-06-17 00:07:37 +02:00
Files
jc/jc/parsers/yaml.py

98 lines
2.1 KiB
Python
Raw Normal View History

2020-02-03 16:20:38 -08:00
"""jc - JSON CLI output utility YAML Parser
2020-02-03 16:12:32 -08:00
Usage:
2020-02-03 16:20:38 -08:00
specify --yaml as the first argument if the piped input is coming from a YAML file
2020-02-03 16:12:32 -08:00
Compatibility:
'linux', 'darwin', 'cygwin', 'win32', 'aix', 'freebsd'
Examples:
$ cat example.yaml | jc --yaml -p
2020-02-03 16:20:38 -08:00
[
{
"Description": "This is a YAML document",
"Number": 42
},
{
"Description": "Yet Another YAML document"
"Boolean": true
}
]
2020-02-03 16:12:32 -08:00
"""
import jc.utils
from ruamel.yaml import YAML
class info():
version = '1.0'
2020-02-03 16:20:38 -08:00
description = 'YAML file parser'
2020-02-03 16:12:32 -08:00
author = 'Kelly Brazil'
author_email = 'kellyjonbrazil@gmail.com'
details = 'Using the ruamel.yaml library at https://pypi.org/project/ruamel.yaml/'
# compatible options: linux, darwin, cygwin, win32, aix, freebsd
compatible = ['linux', 'darwin', 'cygwin', 'win32', 'aix', 'freebsd']
__version__ = info.version
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
2020-02-03 16:17:29 -08:00
List of dictionaries. Each dictionary represents a YAML document:
2020-02-03 16:12:32 -08:00
[
{
2020-02-03 16:17:29 -08:00
YAML Document converted to a Dictionary
See https://pypi.org/project/ruamel.yaml for details
2020-02-03 16:12:32 -08:00
}
]
"""
2020-02-03 16:17:29 -08:00
# No further processing
2020-02-03 16:12:32 -08:00
return proc_data
def parse(data, raw=False, quiet=False):
"""
Main text parsing function
Parameters:
data: (string) text data to parse
raw: (boolean) output preprocessed JSON if True
quiet: (boolean) suppress warning messages if True
Returns:
List of dictionaries. Raw or processed structured data.
"""
if not quiet:
jc.utils.compatibility(__name__, info.compatible)
raw_output = []
2020-02-03 16:17:29 -08:00
# support multiple documents in a file
2020-02-03 16:12:32 -08:00
cleandata = data.split('---')
if cleandata:
for document in cleandata:
yaml = YAML(typ='safe')
raw_output.append(yaml.load(document))
if raw:
return raw_output
else:
return process(raw_output)