1
我想弄清楚如何解析下面的JSON,而不必明確指出多個命令中的數組索引。我只需要將主機組與所有主機信息關聯在一行上。如何使用jq遍歷Nagios JSON
{
"data": {
"selectors": {
},
"hostgroups": [
{
"name": "ATL",
"hosts": [
{
"name": "ATL-SERVER1",
"time_up": 2496629,
"time_down": 8970,
"time_unreachable": 0,
"scheduled_time_up": 0,
"scheduled_time_down": 0,
"scheduled_time_unreachable": 0,
"time_indeterminate_nodata": 0,
"time_indeterminate_notrunning": 0
},
{
"name": "ATL-SERVER2",
"time_up": 2505525,
"time_down": 74,
"time_unreachable": 0,
"scheduled_time_up": 0,
"scheduled_time_down": 0,
"scheduled_time_unreachable": 0,
"time_indeterminate_nodata": 0,
"time_indeterminate_notrunning": 0
}
]
},
{
"name": "LAX",
"hosts": [
{
"name": "LAX-SERVER1",
"time_up": 2505599,
"time_down": 0,
"time_unreachable": 0,
"scheduled_time_up": 0,
"scheduled_time_down": 0,
"scheduled_time_unreachable": 0,
"time_indeterminate_nodata": 0,
"time_indeterminate_notrunning": 0
},
{
"name": "LAX-SERVER2",
"time_up": 2505599,
"time_down": 0,
"time_unreachable": 0,
"scheduled_time_up": 0,
"scheduled_time_down": 0,
"scheduled_time_unreachable": 0,
"time_indeterminate_nodata": 0,
"time_indeterminate_notrunning": 0
}
]
}
]
}
}
以下命令將得到我我需要什麼:
.data.hostgroups[0].name as $Group | {$Group} + .data.hostgroups[0].hosts[] | [.Group, .name, .time_up, .time_down, .time_unreachable, .scheduled_time_up, .scheduled_time_down, .scheduled_time_unreachable, .time_indeterminate_nodata, .time_indeterminate_notrunning] | @csv
.data.hostgroups[1].name as $Group | {$Group} + .data.hostgroups[1].hosts[] | [.Group, .name, .time_up, .time_down, .time_unreachable, .scheduled_time_up, .scheduled_time_down, .scheduled_time_unreachable, .time_indeterminate_nodata, .time_indeterminate_notrunning] | @csv
但我一直在試圖找出如何在一行中做到這一點。我有20個主機組,所以這是我的腳本中的20個命令。
我發現的所有可比較的例子似乎只適用於從數組中拉出單個字段(在我的例子中它是主機[])。例如,這將很好地工作:
map(.data.hostgroups | map({Group: .name, Host: .hosts[].name} | [.Group, .Host])) | add[] | @csv
,輸出是:
"ATL","ATL-SERVER1"
"ATL","ATL-SERVER2"
"LAX","LAX-SERVER1"
"LAX","LAX-SERVER2"
但是當我在添加其他字段,例如:
map(.data.hostgroups | map({Group: .name, Host: .hosts[].name, Uptime: .hosts[].time_up} | [.Group, .Host, .Uptime])) | add[] | @csv
的輸出是:
"ATL","ATL-SERVER1",2496629
"ATL","ATL-SERVER1",2505525
"ATL","ATL-SERVER2",2496629
"ATL","ATL-SERVER2",2505525
"LAX","LAX-SERVER1",2505599
"LAX","LAX-SERVER1",2505599
"LAX","LAX-SERVER2",2505599
"LAX","LAX-SERVER2",2505599
對於每個字段I a dd,它基本上將它們相乘。我很確定我明白這是爲什麼,但我仍然試圖弄清楚如何排除這種情況,同時避免將結果以指數方式組合的問題。
任何人都可以幫我嗎?
謝謝!
非常感謝。它對我有效,我明白爲什麼現在這是必要的。我明白了| .host []正常運行,我明白現在循環是如何工作的。非常感謝! –