otupy.encoders.json.JSONEncoder

class JSONEncoder

Bases: Encoder

JSON Encoder

This class implements the Encoder interface for the JSON format. It leverages the intermediary dictionary representation.

The JSONEncoder can be used to create an OpenC2 stack in Consumer and Producer.

Methods

decode

Decode an OpenC2 message

encode

Encode an OpenC2 object

fromdict

Create an object from dictionary

getName

Encoder name

todict

Convert object to dictionary

Attributes

encoder_type

The label that is used to identify this Encoder in OpenC2 messages.

is_binary

static decode(msg, msgtype=None)

Decode an OpenC2 message

This method is used to create an otupy object of type msgtype from a json record. The otupy class msgtype corresponding to the json record msg must be explicitly provided, since parsing and automatically inferring the msgtype is not currently implemented.

The implementation leverages the intermediary dictionary representation and it is therefore agnostic of otupy classes.

Parameters:
  • msg – The json record to decode.

  • msgtype – The otupy class to convert the json to.

Returns:

An msgtype class initialized according to the json content.

static encode(obj)

Encode an OpenC2 object

This method is used to encode an otupy object, which usually is a Command or Message. The implementation leverages the intermediary dictionary representation and it is therefore agnostic of otupy clases.

Parameters:

obj – A valid otupy object.

Returns:

A string with the json representation of the obj.

encoder_type = 'json'

The label that is used to identify this Encoder in OpenC2 messages.

static fromdict(clstype, dic)

Create an object from dictionary

This is an internal method to create an otupy object from a dictionary. The dictionary must be compliant with the OpenC2 syntax rules. Derived classes are expected to create this intermediate representation and use this method in the encode method. It is necessary to provide the class definition of the otupy object to be instantiated.

Parameters:
  • clstype – The class definition that must be used to instantiate the object.

  • dic – The dictionary with the OpenC2 description.

Returns:

An instance of clstype initialized with the data in the dic.

classmethod getName()

Encoder name

This method MUST be implemented to return the name of the encoding format. The name should be highly representative, possible using official terminology (e.g.: json, xml).

Returns:

The class name.

static todict(obj)

Convert object to dictionary

This is an internal method to convert an otupy object into a dictionary. The dictionary is structured according to OpenC2 syntax.

This method should only be invoked by derived classes to get the intermediary representation of otupy objects. It will likely be used in the implementation of the decode method. :param obj: The otupy object to convert into a dictionary. :return: A dictionary compliant with the OpenC2 syntax rules.