Skip to content
  • There are no suggestions because the search field is empty.

How-To: Convert an OPC UA Payload to an Array

What Does This Article Cover?

This article provides configuration recommendations and a JavaScript code snippet that can be used to convert an OPC UA payload to an array. An OPC UA payload has a hierarchical structure when obtained by an Intelligence Hub Connection Input. In some cases it is beneficial to process the payload as an array. This article provides a solution to achieve this.

What is converting to an array?

In this context converting to an array refers to changing the JSON structure from a hierarchy of objects to an array. Practically this means the following.

Changing a data payload from looking like this.

{
    "TestDevice1": {
        "AirPressure": 84.39658,
        "AssetID": "ABC"
    },
    "TestDevice2": {
        "AirPressure": 74.39658,
        "AssetID": "DEF"
    }
}

To look like this.

[
    {
        "value_id": "TestDevice1.AirPressure",
        "value": 84.39658
    },
    {
        "value_id": "TestDevice1.AssetID",
        "value": "ABC"
    },
    {
        "value_id": "TestDevice2.AirPressure",
        "value": 74.39658
    },
    {
        "value_id": "TestDevice2.AssetID",
        "value": "DEF"
    }
]

How to Configure a Solution

In Intelligence Hub versions 3.4 and earlier JavaScript code can be used to alter the format of the payload. The JavaScript code can be applied in Custom Condition or Pipeline Transform Stage.

The following is JavaScript code that could be used in a Custom Condition.

function flattenObjectWithValues(obj, prefix = '') {
    let result = [];
    for (let key in obj) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
            result = result.concat(flattenObjectWithValues(obj[key], `${prefix}${key}.`));
        } else {
            result.push({ value_id: `${prefix}${key}`, value: obj[key] });
        }
    }
    return (result);
}
flattenObjectWithValues(this.currentValue, ``)

Considerations

The code provided above is formatted for a Custom Condition. The code needs to be slightly modified for use in an Intelligence Hub Pipeline Transform Stage.

Note that this solution assumes that an OPC UA Branch Input is being used.

Other related material: