简体   繁体   English

在数组JSONata中包含计数器

[英]Include Counter in array JSONata

I just started using JSONata and I found it quite fascinating to parse JSON easily. 我刚开始使用JSONata,我发现它很容易解析JSON。 But I have this problem, and I'm not sure if it can be done with JSONata directly. 但是我有这个问题,我不确定是否可以直接使用JSONata完成。

I want to include a counter that goes from 1 to "the number of objects in an array", like so: 我想包括一个从1到“数组中对象数”的计数器,如下所示:

Original output from JSONata expression: JSONata表达式的原始输出:

[ { "a": false, "b": "", "c": "", "d": true }, { "a": false, "b": "", "c": "", "d": true }, { "a": false, "b": "", "c": "", "d": true } ] [{“ a”:false,“ b”:“”,“ c”:“”,“ d”:true},{“ a”:false,“ b”:“”,“ c”:“”, “ d”:true},{“ a”:false,“ b”:“”,“ c”:“”,“ d”:true}]

Wanted output: 想要的输出:

[ { "count": "1", "a": false, "b": "", "c": "", "d": true }, { "count": "2", "a": false, "b": "", "c": "", "d": true }, { "count": "3", "a": false, "b": "", "c": "", "d": true } ] [{“ count”:“ 1”,“ a”:false,“ b”:“”,“ c”:“”,“ d”:true},{“ count”:“ 2”,“ a”: false,“ b”:“”,“ c”:“”,“ d”:true},{“ count”:“ 3”,“ a”:false,“ b”:“”,“ c”:“ “,” d“:true}]

Is it possible? 可能吗? Thank you in advance. 先感谢您。

You can use the $map() function to iterate over a list and apply an expression to each item. 您可以使用$ map()函数遍历列表并将表达式应用于每个项目。 The second argument of your function will be the index within the array. 函数的第二个参数将是数组中的索引。 So for your example, the following will merge the count property into your original array of objects: 因此,对于您的示例,以下内容将count属性合并到您的原始对象数组中:

$ ~> $map(function($v, $i) {
  $merge([{'count': $i+1}, $v])
})

See this working in the JSONata Exerciser: http://try.jsonata.org/rkDpyXMVM 在JSONata Exerciser中查看此工作: http ://try.jsonata.org/rkDpyXMVM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM