Rens Groenveld
Rens Groenveld

Reputation: 982

Azure Stream Analytics convert array values

Very specific question, if I have the following input in my Streaming Analytics component:

 //some input
 "outputs": [
  {
    "name": "output1",
    "unit": "unit1",
    "value": "95813"
  },
  {
    "name": "output2",
    "unit": "unit2",
    "value": "303883"
  }, // and more array values

How can I get a JSON result that would look as follows:

"outputs":[ {
   "output1":95813,
   "output2":303883
   //etc
 }]

So, I don't need the unit value, and to save space, I'd like to use the 'name' as the key, and the 'value' as the value of the key-value array. This is my current query:

SELECT
input.outputs as outputs
INTO "to-mongodb"
FROM "from-iothub" input

but this of course creates seperate JSON arrays, with the same structure as I do get as my input.

Anyone any idea on how to do this?

In worst case, just filtering out the 'unit' would also already be a great help.

Thanks in advance

Upvotes: 1

Views: 803

Answers (1)

Jay Gong
Jay Gong

Reputation: 23792

You could use user-defined functions in Azure Stream Analytics. Please refer to the sample function I tested for you.

UDF:

function main(arg) {
    var array = arg.outputs;
    var returnJson = {};
    var outputArray = [];
    var map = {};
    for(var i=0;i<array.length;i++){        
        var key=array[i].name;        
        map[key] = array[i].value;      
    }
    outputArray.push(map);
    returnJson = {"outputs" : outputArray};
    return returnJson;  
}

Query:

WITH 
c AS
(
    SELECT 
    udf.processArray(jsoninput) as result
    from jsoninput
)
SELECT
    c.result
INTO
    jaycosmostest
FROM
    c

Test Output:

enter image description here

Hope it helps you.

Upvotes: 2

Related Questions