我已经通过带有curl请求的公共API生成了一个json文件:
curl "https://gbfs.citibikenyc.com/gbfs/es/station_status.json" > citibike.json
此漂亮的图片在jq
中的显示方式为:
$ jq . citibike.json
{
"last_updated": 1537986541,
"ttl": 10,
"data": {
"stations": [
{
"station_id": "304",
"num_bikes_available": 22,
"num_ebikes_available": 0,
"num_bikes_disabled": 4,
"num_docks_available": 7,
"num_docks_disabled": 0,
"is_installed": 1,
"is_renting": 1,
"is_returning": 0,
"last_reported": 1537986269,
"eightd_has_available_keys": true,
"eightd_active_station_services": [
{
"id": "a58d9e34-2f28-40eb-b4a6-c8c01375657a"
}
]
},
{
"station_id": "359",
"num_bikes_available": 0,
"num_ebikes_available": 0,
"num_bikes_disabled": 2,
"num_docks_available": 50,
"num_docks_disabled": 1,
"is_installed": 1,
"is_renting": 1,
"is_returning": 0,
"last_reported": 1537986120,
"eightd_has_available_keys": false,
"eightd_active_station_services": [
{
"id": "2e104e31-606a-44af-8b25-ceaffc338489"
}
]
},...
我的目标是得到两个数字-通过一个jq查询获得num_bikes_available
和num_ebikes_available
中包含的所有值的总和。
以下尝试会引发错误:
jq -n 'reduce (inputs | .data.stations[] ) as $i ({}; .[$i.num_bikes_available] += $i.value)' citibike.json
jq 'reduce .data.stations[] as $num_bikes_available (0; . + $num_bikes_available)' citibike.json
关于为什么以及如何产生期望结果的任何想法?
答案 0 :(得分:1)
使用您的输入(呈现为有效JSON),过滤器:
.data.stations
| { bikes: map(.num_bikes_available) | add,
ebikes: map(.num_ebikes_available) | add }
产生:
{
"bikes": 22,
"ebikes": 0
}
更有效的解决方案将使用sigma
,例如如下:
def sigma(s): reduce s as $x (0; .+$x);
.data.stations
| [sigma(.[] | .num_bikes_available),
sigma(.[] | .num_ebikes_available)]