使用nebius-cloud-cli
,我试图仅列出我帐户中所有文件夹的名称和id。
我试过了:
yc vpc networks list --format json | jq ".[] "
我得到的输出是:
{
"id": "ccm979ujel7gpcq6aulc",
"folder_id": "b489aa1fe17nphuomth8",
"created_at": "2022-12-12T17:47:24Z",
"name": "default",
"description": "Auto-created network"
}
{
"id": "ccmn8qvg1uaaaiblc05e",
"folder_id": "b4aaav1fe1gnphuomth8",
"created_at": "2022-12-29T12:07:40Z",
"name": "my-network"
}
{
"id": "campid2asepq3bc68fn6",
"folder_id": "b489kv3ae1ga1huomth8",
"created_at": "2021-12-18T09:54:01Z",
"name": "my-nw",
"description": "Auto-created network"
}
预期输出:
[
{"name": "default",
"folder_id": "b4aaav1fe1gnphuomth8"
},
{"name": my-nw,
"folder_id": "b489kv3ae1ga1huomth8"
}
]
Try it out
我得到的输出是来自这个输出的多行非标准JSON,需要正确处理。
我正在寻找一个简单的转换,而不是重定向和awks和像bash中的<<
这样的东西,这违背了目的。
使用map({ name, folder_id })
和--slurp
:
command | jq --slurp 'map({ name, folder_id })'
输入:
--slurp
不是为输入中的每个JSON对象运行过滤器,而是将整个输入流读入一个大数组并只运行一次过滤器。
文档
{
"id": "ccm979ujel7gpcq6aulc",
"folder_id": "b489aa1fe17nphuomth8",
"created_at": "2022-12-12T17:47:24Z",
"name": "default",
"description": "Auto-created network"
}
{
"id": "ccmn8qvg1uaaaiblc05e",
"folder_id": "b4aaav1fe1gnphuomth8",
"created_at": "2022-12-29T12:07:40Z",
"name": "my-network"
}
{
"id": "campid2asepq3bc68fn6",
"folder_id": "b489kv3ae1ga1huomth8",
"created_at": "2021-12-18T09:54:01Z",
"name": "my-nw",
"description": "Auto-created network"
}
输出[
{
"name": "default",
"folder_id": "b489aa1fe17nphuomth8"
},
{
"name": "my-network",
"folder_id": "b4aaav1fe1gnphuomth8"
},
{
"name": "my-nw",
"folder_id": "b489kv3ae1ga1huomth8"
}
]
演示<JqPlay演示/em>
由于您在问题中使用.[]
,这使我认为该命令的输出是一个数组。使用map
对数组中的每个项应用转换:
$ yc ...
[
{...},
{...}
]
$ yc ... | jq 'map({ name, folder_id })'
[
{...},
{...}
]
.[]
流数组的所有项。要转换流,使用不带map的对象构造:
$ yc ...
[
{...},
{...}
]
$ yc ... | jq '.[] | { name, folder_id }'
{...}
{...}
或者如果yc输出多个JSON对象,那么不要直接流式传输和转换:
$ yc ...
{...}
{...}
$ yc ... | jq '{ name, folder_id }'
{...}
{...}
如果yc的输出实际上是一个具有多个属性的单个对象,您仍然可以像使用常规数组一样使用map;它只会自动返回属性的值:
$ yc ...
{
"a": {...},
"b": {...}
}
$ yc ... | jq 'map({ name, folder_id })'
[
{...},
{...}
]
如果yc输出多个JSON对象,并且您需要将输出作为一个数组,那么使用-s
/--slurp
将输入放入一个大数组中,然后应用map操作:
$ yc ...
{...}
{...}
$ yc ... | jq -s 'map({ name, folder_id })'
[
{...},
{...}
]
假设调用yc vpc networks list --format json
本身会产生类似
{
"networks": [
{
"id": "4e8a4034-a973-4f1f-84a8-73ea54adcee1",
"name": "my-network",
"description": "My network",
"created_at": "2022-01-01T00:00:00Z",
"folder_id": "b1g7f0d3-2e0a-4714-ba6a-b1g7f0d32e0a",
"vpc_id": "b1g7f0d3-2e0a-4714-ba6a-b1g7f0d32e0a",
"region_id": "ru-central1"
}
]
}
然后将其导入jq '.networks | map({name, folder_id})'
将得到
[
{
"name": "my-network",
"folder_id": "b1g7f0d3-2e0a-4714-ba6a-b1g7f0d32e0a"
}
]
演示