0

我正在使用流分析查询来过滤我输入的复杂 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 数组包装到具有唯一“id”的 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\"}"
  }
]

有没有办法用查询包装该数组中的所有嵌套对象?

4

1 回答 1

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;
}

询问

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"
         }
       ]
     }
  ]
}

输出

在此处输入图像描述

于 2017-04-24T10:56:56.727 回答