0

I have a stream of JSON arrays like this

[{"id":"AQ","Count":0}]
[{"id":"AR","Count":1},{"id":"AR","Count":3},{"id":"AR","Count":13},
{"id":"AR","Count":12},{"id":"AR","Count":5}]
[{"id":"AS","Count":0}]

I want to use jq to get a new json like this

{"id":"AQ","Count":0}
{"id":"AR","Count":34}
{"id":"AS","Count":0}

34=1+3+13+12+5 which are in the second array. I don't know how to describe it in detail. But the basic idea is shown in my example. I use bash and prefer to use jq to solve this problem. Thank you!

4

3 回答 3

2

如果您想要一个高效但通用的解决方案,它不假设每个输入数组具有相同的 id,那么以下帮助函数使解决方案变得简单:

# Input: a JSON object representing the subtotals
# Output: the object augmented with additional subtotals
def adder(stream; id; filter):
  reduce stream as $s (.; .[$s|id] += ($s|filter));

假设您的 jq 有inputs,那么最有效的方法是使用它(但请记住使用 -n 命令行选项):

reduce inputs as $row ({}; adder($row[]; .id; .Count) )

这会产生:

{"AQ":0,"AR":34,"AS":0}

从这里,很容易得到你想要的答案,例如使用to_entries[] | {(.key): .value}

如果您的 jq 没有inputs并且您不想升级,则使用 -s 选项(而不是 -n)并替换inputs.[]

于 2017-07-19T16:29:24.347 回答
1

假设每个数组中的 .id 相同:

first + {Count: map(.Count) | add}

或者更容易理解:

(map(.Count) | add) as $sum | first | .Count = $sum

或者更明确地说:

{ id: (first|.id), Count: (map(.Count) | add) }
于 2017-07-19T16:00:48.303 回答
0

这有点笨拙,但考虑到您的输入:

jq -c '
  reduce .[] as $item ({}; .[($item.id)] += ($item.Count))
  | to_entries
  | .[] | {"id": .key, "Count": .value}
'

产生输出:

{"id":"AQ","Count":0}
{"id":"AR","Count":34}
{"id":"AS","Count":0}
于 2017-07-19T15:35:52.823 回答