This article provides a template and a sample script in JavaScript for parsing data that is sent to custom topics.

Script template

var SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update' // The custom topic /user/update.
var SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error' // The custom topic /user/update/error.
/**
 * Call a function to convert the data that is sent by a device to a custom topic into JSON-formatted data when the device reports data to IoT Platform.
 * topic: an input parameter that specifies the topic to which the device sends messages. The value is a string.    
 * rawData: an input parameter. The value is a byte array that cannot be empty.
 * jsonObj: an output parameter. The value is a JSON object that cannot be empty.
 */
function transformPayload(topic, rawData) {
var jsonObj = {};
return jsonObj;
}

Sample script

Note The following sample script can be used only to parse data that is sent to custom topics. If the Data Type parameter of the product is set to Custom, you also need to write a script for parsing Thing Specification Language (TSL) data. For information about how to write a script for parsing TSL data, see Example for parsing TSL data.
var SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update' // The custom topic /user/update.
var SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error' // The custom topic /user/update/error.
/*
  Sample data
  Custom topic:
     /user/update, to which data is sent.
  Input parameters:
     topic: /{productKey}/{deviceName}/user/update
     bytes: 0x000000000100320100000000
  Output parameters:
  {
     "prop_float": 0,
     "prop_int16": 50,
     "prop_bool": 1,
     "topic": "/{productKey}/{deviceName}/user/update"
   }
 */
function transformPayload(topic, bytes) {
    var uint8Array = new Uint8Array(bytes.length);
    for (var i = 0; i < bytes.length; i++) {
        uint8Array[i] = bytes[i] & 0xff;
    }
    var dataView = new DataView(uint8Array.buffer, 0);
    var jsonMap = {};

    if(topic.includes(SELF_DEFINE_TOPIC_ERROR_FLAG)) {
        jsonMap['topic'] = topic;
        jsonMap['errorCode'] = dataView.getInt8(0)
    } else if (topic.includes(SELF_DEFINE_TOPIC_UPDATE_FLAG)) {
        jsonMap['topic'] = topic;
        jsonMap['prop_int16'] = dataView.getInt16(5);
        jsonMap['prop_bool'] = uint8Array[7];
        jsonMap['prop_float'] = dataView.getFloat32(8);
    }

    return jsonMap;
}