我正在使用Stream Analytics查询来过滤我输入的Complex 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\"}"
}
]
有没有办法用查询包装该数组中的所有嵌套对象?
答案 0 :(得分: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"
}
]
}
]
}
<强>输出强>