我有以下JSON数据:
[
{
"Russia": 1073849
}
]
[
{
"Spain": 593730
}
]
[
{
"France": 387252
}
]
[
{
"UK": 371125
}
]
所需的输出:
[
{
"Russia": 1073849
},
{
"Spain": 593730
},
{
"France": 387252
},
{
"UK": 371125
}
]
基于类似的问题,我尝试了'.[]|transpose|map(add)'
,但它给出了一个错误:无法用数字索引对象。我也不能group_by(key)
,因为对象中没有公用密钥。
答案 0 :(得分:1)
如果我理解正确,您想产生一个数组作为输出。您可以将数组包装器从最终对象周围移到整个jq
调用中,以执行以下操作:
curl -s https://corona-stats.online/\?format\=json |
jq '[ .data[]
| select(.continent | test("Europe"))
| {(.country): .cases}
]'
| [0:4]
之后的输出:
[
{
"Russia": 1073849
},
{
"Spain": 603167
},
{
"France": 395104
},
{
"UK": 374228
}
]
如果需要对象,可以使用:
curl -s https://corona-stats.online/\?format\=json |
jq '[ .data[]
| select(.continent | test("Europe"))
]
| map({(.country): .cases})
| add'
或:
curl -s https://corona-stats.online/\?format\=json |
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")
,因为精度较低。
答案 1 :(得分:1)
假设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