Skip to content

Instantly share code, notes, and snippets.

@kellyjonbrazil
Created September 15, 2020 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellyjonbrazil/7d67cfa003735bf80ef43fe5652950dd to your computer and use it in GitHub Desktop.
Save kellyjonbrazil/7d67cfa003735bf80ef43fe5652950dd to your computer and use it in GitHub Desktop.
Saltstack JC Serializer
"""
salt.serializers.jc
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implements JC serializer.
JC converts the output of many commands and file-types to structured format.
https://github.com/kellyjonbrazil/jc
Requires JC is installed via pip: $ pip3 install jc
Requires Python >= 3.6
"""
import importlib
# Import Salt libs
from salt.serializers import DeserializationError
# Import jc
try:
import jc
available = True
except ImportError:
available = False
__all__ = ["deserialize", "available"]
class NotImplementedError(DeserializationError):
pass
def deserialize(stream_or_string, parser=None):
"""
Deserialize from raw command output into Python data structure.
:param stream_or_string: command output stream or string to deserialize.
:param parser: parser used to serialze the command output
"""
if not available:
raise DeserializationError('You need to install "jc" prior to running the jc deserializer')
if not parser:
raise DeserializationError("You must specify a parser for the jc deserializer. e.g. parser='uptime'")
try:
jc_parser = importlib.import_module('jc.parsers.' + parser)
if not isinstance(stream_or_string, (bytes, str)):
return jc_parser.parse(stream_or_string, quiet=True)
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode("utf-8")
return jc_parser.parse(stream_or_string, quiet=True)
except Exception as error:
raise DeserializationError(error)
def serialize(obj, **options):
raise NotImplementedError("JC can only deserialize.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment