jq如何合并多个数组?

问题描述 投票:0回答:2

我有以下数据,多个jq管道的输出:

 [
   {
     "Russia": 1073849
   }
 ]
 [
   {
     "Spain": 593730
   }
 ]
 [
   {
     "France": 387252
   }
 ]
 [
   {
     "UK": 371125
   }
 ]

我想要的输出是:

 [
   {
     "Russia": 1073849
   },
   {
     "Spain": 593730
   },
   {
     "France": 387252
   },
   {
     "UK": 371125
   }
 ]

基于类似的问题,我尝试了

'.[]|transpose|map(add)'
,但它给出了错误:
Cannot index object with number
。我也不能
group_by(key)
,因为对象中没有公共密钥。

json jq
2个回答
7
投票

假设

input.json
文件是:

[{"Russia": 1073849}]
[{"Spain": 593730}]
[{"France": 387252}]
[{ "UK": 371125}]

然后这个:

jq -s 'reduce .[] as $x ([]; . + $x)' input.json

返回:

[
  {
    "Russia": 1073849
  },
  {
    "Spain": 593730
  },
  {
    "France": 387252
  },
  {
    "UK": 371125
  }
]

备注:

  • jq
    可以使用
    +
    运算符合并数组,例如
    [1]+[2]
    返回
    [1,2]
  • -s
    标志读取
    input.json
    并将所有条目放入数组中。所以你最终得到了一个数组数组,你可以将其与
    reduce
    合并。

这可以进一步简化:

jq -s 'add' input.json

3
投票

如果我理解正确,您想要生成一个数组作为输出。您可以将数组包装器从最终对象周围移动到整个

jq
调用来执行此操作:

url=https://raw.githubusercontent.com/qualified/challenge-data/605fb67/corona.json
curl -s $url | 
jq '[ .data[] 
      | select(.continent | test("Europe"))
      | {(.country): .cases} 
    ]'

| [0:4]
后输出:

[
  {
    "Russia": 1073849
  },
  {
    "Spain": 603167
  },
  {
    "France": 395104
  },
  {
    "UK": 374228
  }
]

如果你想要一个对象,你可以使用:

curl -s $url | 
jq '[ .data[]
      | select(.continent | test("Europe"))
    ] 
    | map({(.country): .cases}) 
    | add'

或:

curl -s $url | 
jq '[ .data[]
      | select(.continent | test("Europe"))
    ]
    | reduce .[] as $e ({}; .[$e.country] = $e.cases)'

输出:

{
  "Russia": 1073849,
  "Spain": 603167,
  "France": 395104,
  "UK": 374228,
  "Italy": 289990,
  "Germany": 264375,
  "Ukraine": 159702,
  "Romania": 105298,
  "Belgium": 94306,
  "Sweden": 87345,
  "Netherlands": 84778,
  "Poland": 75134,
  "Belarus": 74552,
  "Portugal": 65021,
  "Switzerland": 47751,
  "Moldova": 43734,
  "Czechia": 38187,
  "Austria": 34305,
  "Serbia": 32511,
  "Ireland": 31549,
  "Bosnia": 23929,
  "Denmark": 20571,
  "Bulgaria": 18061,
  "Macedonia": 15925,
  "Hungary": 13879,
  "Croatia": 13749,
  "Greece": 13730,
  "Norway": 12330,
  "Albania": 11672,
  "Finland": 8725,
  "Luxembourg": 7244,
  "Montenegro": 6900,
  "Slovakia": 5768,
  "Slovenia": 3831,
  "Lithuania": 3397,
  "Estonia": 2722,
  "Malta": 2454,
  "Iceland": 2174,
  "Latvia": 1482,
  "Andorra": 1438,
  "San Marino": 723,
  "Channel Islands": 639,
  "Faroe Islands": 428,
  "Isle of Man": 339,
  "Gibraltar": 334,
  "Monaco": 177,
  "Liechtenstein": 111,
  "Holy See (Vatican City State)": 12
}

虽然在这个数据集上并不重要,但我更喜欢使用

== "Europe"
而不是
test("Europe")
,后者有点不太精确。

© www.soinside.com 2019 - 2024. All rights reserved.