Tuesday Tip: Use the Mutate Node for complex payload transformations

The Mutate Node can construct complex objects and arrays when combined with Handlebar helpers like each.

For example, when reading data from OPC UA devices, I like to use attribute tags on peripheral devices to store the namespace and identifier. Since peripherals are automatically synced to edge devices, we can use these attribute tags to know how to read this specific device instead of hard coding this information directly in the workflow.

In the edge workflow, when you use the Peripheral: Get Node to query this edge device’s peripherals, those attribute tags are automatically available on the payload:

This is where the Mutate Node comes in. We need to transform the array of attributes and attribute tags into the array structure that the OPC UA: Read Node expects.

Here’s the template used in the screenshot above:

[
{{#each working.peripheral.attributes}}
  {{#with this.attributeTags as |tags|}}
    {
      "nameSpace": {{jsonEncode tags.namespace}},
      "identifier": {{jsonEncode tags.identifier}},
      "key": {{jsonEncode ../this.name}}
    }
    {{#unless @last}},{{/unless}}
  {{/with}}
{{/each}}
]

This template is generating a JSON string. When you check the Treat value as JSON option, Losant will automatically decode that string to an object on the payload.

image

This can now be directly passed to the OPC UA: Read Node to perform the read operations:

The advantage to using this option vs using the Function Node is for workflow performance. The Mutate Node is considerably faster to execute when compared to the Function Node.