0

我正在使用流分析查詢來過濾我輸入的複雜Json對象。將JSON包裝到輸出流分析查詢中

輸入:

{ 
    "id" : "001", 
    "firstArray":[ 
    { 
     "tid" : 9, 
     "secondArray":[ 
     { 
      "key1" : "value1", 
      "key2" : "value2" 
     }, 
     {...} 
     ] 
    }, 
    { 
     "tid" : 8, 
     "secondArray":[ 
     { 
      "key1" : "value1", 
      "key2" : "value2" 
     }, 
     {...} 
     ] 
    } 
    ] 
} 

這是我的查詢:

WITH T1 AS 
    (
    SELECT 
     FirstArray.ArrayValue.Tid as Tid, 
     FirstArray.ArrayValue.secondArray as SecondArray 
    FROM 
     inputfromeventhub MySource 
    OUTER APPLY GetElements(MySource.firstArray) AS FirstArray 
    ) 
SELECT 
    T1.Tid as Tid, 
    SecondArray.ArrayValue.key1 as key1, 
    SecondArray.ArrayValue.key2 as key2 
INTO exitstream 
OUTER APPLY GetElements(T1.SecondArray) as SecondArray 

我得到的是這樣的:

[ 
{ 
    "tid":9, 
    "key1": "value1", 
    "key2": "value2" 
}, 
{ 
    "tid":8, 
    "key1": "value1", 
    "key2": "value2" 
} 
] 

我想換這個JSON數組轉換成一個JSON對象與一個獨特的'身份證'來得到像這樣的東西:

{ 
"id":"001", 
"array":[ 
    { 
    "tid":9, 
    "key1": "value1", 
    "key2": "value2" 
    }, 
    { 
    "tid":8, 
    "key1": "value1", 
    "key2": "value2" 
    } 
] 
} 

我找不到辦法做到這一點。我試圖創建一個第三選擇調用一個用戶定義的函數:

function main(obj) { 
    var out_obj = {}; 
    out_obj.id = "001"; 
    out_obj.array = obj; 

    return JSON.stringify(out_obj); 
} 

但這陣列中應用到每個對象..所以我得到這樣的:

[ 
    { "myFunction": "{\"id\":\"001\",\"array{\"tid\":9,\"key1\":\"value1\",\"key2\":\"value2\"}" 
    }, 
    { "myFunction": "{\"id\":\"001\",\"array{\"tid\":8,\"key1\":\"value1\",\"key2\":\"value2\"}" 
    } 
] 

有沒有辦法來包裝該數組中的所有嵌套對象都帶有查詢?

回答

0

根據您的要求,我測試了這個問題,你可以參考下面的代碼片段:

JavaScript的UDF

function main(obj) { 
    var out_obj = []; 
    for(var i=0;i<obj.length;i++){ 
    var o=obj[i]; 
    for(var j=0;j<o.secondArray.length;j++){ 
     o1=o.secondArray[j]; 
     out_obj.push({tid:o.tid,key1:o1.key1,key2:o1.key2}); 
    } 
    } 
    return out_obj; 
} 

QUERY

SELECT 
    MySource.id, 
    udf.aggreate(MySource.firstArray) as array 
FROM 
    [inputfromeventhub] MySource 

輸入

{ 
    "id" : "001", 
    "firstArray":[ 
    { 
     "tid" : 9, 
     "secondArray":[ 
     { 
      "key1" : "value01", 
      "key2" : "value02" 
     }, 
     { 
      "key1" : "value03", 
      "key2" : "value04" 
     } 
     ] 
    }, 
    { 
     "tid" : 8, 
     "secondArray":[ 
     { 
      "key1" : "value11", 
      "key2" : "value12" 
     }, 
     { 
      "key1" : "value13", 
      "key2" : "value14" 
     } 
     ] 
    } 
    ] 
} 

輸出

enter image description here

+0

這正是我想要的, 非常感謝布魯斯 – Sam