Procedure for Calling Python JER Encode

The procedure to call a Python encode method for the different cases described above is basically the same. It involves the following three steps:

  1. Create an encode message buffer object into which the value will be encoded.

  2. Invoke the encode method.

The first step is the creation of an encode message buffer object. This is done by simply creating an instance of the Asn1JsonEncodeBuffer class:

  # Encode to a file
  encbuf = Asn1JsonEncodeBuffer(filename="filename")
  
  # Or, encode to a TextIOBase object, such as StringIO
  encbuf = Asn1JsonEncodeBuffer(writer=text_io_object)

The encode method is then invoked. In the simple case of a primitive type with no generated class, this involves invoking one of the methods defined in the encode buffer class to encode a primitive value. For example, to encode an integer, one would do:

encbuf.write(str(value))

The procedure for invoking a static method is similar. The general form is <classname>.json_encode(encbuf, value). So, for example, a class named EmployeeNumber would be generated for the following definition:

EmployeeNumber ::= INTEGER(0..100)

To encode an employee number of 51, one would do the following:

EmployeeNumber.json_encode(encbuf, 51)

This would verify the constraint was satisfied and encode the value 51.

Finally, to invoke the instance method in the class generated for a constructed type, one would first populate the attribute values and then invoke the encode method. To encode an instance of the Name class in the employee sample, one would first create an instance of the class, populate the attributes, and then invoke the encode method:

jSmithName = Name()
jSmithName.givenName = 'John'
jSmithName.initial = 'P'
jSmithName.familyName = 'Smith'

jSmithName.json_encode(encbuf)

This will encode the name.

A complete example showing how to invoke an encode method is as follows:

# Note: jSmithPR object was previously populated with data

try:
    jSmithPR = PersonnelRecord()

    # Step 1: Create an encode buffer object
    encbuf = Asn1JsonEncodeBuffer(filename=out_filename)
    
    # Step 2: Invoke the encode method.
    jSmithPR.json_encode(encbuf)
    
    encbuf.close()

except Exception:
    print(traceback.format_exc())
    sys.exit(-1)