我有一个冗长的JSON文件,我执行命令以获取如下所示的输出:
jq -s '.[]
| ."lrouter/show"[]
| del( . | select(.type == "TUNNEL-VRF"))
| del(.ports[] | select(.type == "blackhole" or .type == "cpu-port" or .type == "loopback"))
| "Name: \(.name)" ,
"UUID: \(.uuid)" ,
(.ports[] | {Port_Name: .name,
Port_Type: .type,
Port_Peer: .peer,
Port_IPs: .ips[],
Port_Admin_Up: .admin_up,
Port_Op_State: .op_state_up } )' ec-state
"Name: SR-t0-uplink"
"UUID: 23354d26-6994-46d9-b78c-bb565a1c13f2"
{
"Port_Name": "uplink",
"Port_Type": "uplink",
"Port_Peer": "d78089f6-71b5-4c8e-a477-69ee01f17c5c",
"Port_IPs": "1.1.13.5/24",
"Port_Admin_Up": true,
"Port_Op_State": true
}
{
"Port_Name": "bp-sr0-port",
"Port_Type": "backplane",
"Port_Peer": null,
"Port_IPs": "169.254.0.2/28",
"Port_Admin_Up": false,
"Port_Op_State": false
}
jq: error (at ec-state:1028): Cannot iterate over null (null)
但是我得到了期望的结果,但是在结果的结尾也得到了jq错误。只是好奇地知道我在查询中做错了什么。
答案 0 :(得分:0)
由于您的输入很大,因此您可以考虑添加断言或等效项。由于您的程序显然希望在各个点上都有数组,因此您可以使用以下函数对其进行检测:
def q($n; $msg):
if type == "array" or type == "object"
then .
else error("\($msg): composite expected @ \($n) vs \(.)")
end;
您的程序可以按以下方式进行检测:
range(0;length) as $n
| .[$n]
| ."lrouter/show" | q($n; 2) | .[]
| del( . | select(.type == "TUNNEL-VRF"))
| del(.ports | q($n; 3) | .[] | select(.type == "blackhole" or .type == "cpu-port" or .type == "loopback"))
| "Name: \(.name)" ,
"UUID: \(.uuid)" ,
(.ports[] | {Port_Name: .name,
Port_Type: .type,
Port_Peer: .peer,
Port_IPs: (.ips | q($n; 4) |.[]),
Port_Admin_Up: .admin_up,
Port_Op_State: .op_state_up } )