我正在尝试创建一个适合所有 jq 命令的单一尺寸来转储包含数据的所有键,例如数字、字符串、空、布尔值
当它命中一个数组值时,我不希望打印数组名称,而是应该查看数组内部并从数组内部提取键名称。
示例输出将是这样的......
coord.lon
coord.lat
weather.0
weather.0.id
weather.0.main
weather.0.description
weather.0.icon
base
我有以下有效的位,但它返回父键,它们是数组,我不需要这些,只需要子键。
jq -r 'paths | map(.|tostring)|join(".")' weather.json
任何人都可以提供任何帮助吗?我挣扎得很厉害。
示例 json
{
"coord": {
"lon": -90.85,
"lat": 38.8
},
"weather": [
{
"id": 501,
"main": "Rain",
"description": "moderate rain",
"icon": "10d"
}
],
"base": "stations",
"main": {
"temp": 38.19,
"pressure": 1020,
"humidity": 100,
"temp_min": 36,
"temp_max": 39.99
},
"visibility": 4023,
"wind": {
"speed": 4.7,
"deg": 330
},
"rain": {
"1h": 1.82
},
"clouds": {
"all": 75
},
"dt": 1572448290,
"sys": {
"type": 1,
"id": 4178,
"country": "US",
"sunrise": 1572438477,
"sunset": 1572476760
},
"timezone": -18000,
"id": 0,
"name": "Wentzville",
"cod": 200
}
答案1
您可以先删除数组,例如:
del(.[] | select(type=="array"))
要仅保留对象,请执行以下操作:
<infile.json jq -r '
del(.[] | select(type!="object")) |
paths |
map(tostring) |
select(length==2) |
join(".")
'
输出:
coord.lon
coord.lat
main.temp
main.pressure
main.humidity
main.temp_min
main.temp_max
wind.speed
wind.deg
rain.1h
clouds.all
sys.type
sys.id
sys.country
sys.sunrise
sys.sunset
编辑
也许您想要两个答案的组合?
paths(scalars) |
select(length >= 2) |
map(tostring) |
join(".")
输出:
coord.lon
coord.lat
weather.0.id
weather.0.main
weather.0.description
weather.0.icon
main.temp
main.pressure
main.humidity
main.temp_min
main.temp_max
wind.speed
wind.deg
rain.1h
clouds.all
sys.type
sys.id
sys.country
sys.sunrise
sys.sunset
答案2
这是工作:
jq -r 'paths(scalars) | map(.|tostring)|join(".")' weather.json
结果
coord.lon
coord.lat
weather.0.id
weather.0.main
weather.0.description
weather.0.icon
base
main.temp
main.pressure
main.humidity
main.temp_min
main.temp_max
visibility
wind.speed
wind.deg
rain.1h
clouds.all
dt
sys.type
sys.id
sys.country
sys.sunrise
sys.sunset
timezone
id
name
cod