如何在一行中使用jq从JSON数组/对象获得多个值?
here curl请求及其响应
curl -s -k --location --request GET "https://${HOSTNAME}/api/v1/projects/myProjects?page=1&pageSize=2" --header "Authorization: Bearer "$token"" | jq -r '.["data"]'
# Response
[
{
"id": "8a70803f8045722601804f62d54c5d9d",
"createdBy": "8a70802980325cdc0180326b5fe60006",
"createdDate": "2022-04-22T03:48:38.860+0000",
"modifiedBy": "8a70802980325cdc0180326b5fe60006",
"modifiedDate": "2022-04-22T03:48:38.860+0000",
"version": null,
"inactive": false,
"name": "Netbank734113",
},
{
"id": "8a70801c804568ae01804f625a923f8d",
"createdBy": "8a70802980325cdc0180326b5fe60006",
"createdDate": "2022-04-22T03:48:07.442+0000",
"modifiedBy": "8a70802980325cdc0180326b5fe60006",
"modifiedDate": "2022-04-22T03:48:07.442+0000",
"version": null,
"inactive": false,
"name": "Netbank734112",
}
]
现在尝试下面的命令在一行中获取id和名称,但是会出现重复的结果。
result=$(curl -s -k --location --request GET "https://${HOSTNAME}/api/v1/projects/myProjects?page=1&pageSize=2" --header "Authorization: Bearer "$token"" | jq -r '.["data"]|.[].name +" "+ .[].id')
echo "$result"
# response
Netbank734113 8a70803f8045722601804f62d54c5d9d
Netbank734112 8a70803f8045722601804f62d54c5d9d
Netbank734113 8a70801c804568ae01804f625a923f8d
Netbank734112 8a70801c804568ae01804f625a923f8d
我如何摆脱那些重复的值,基本上得到下面的响应?
Netbank734113 8a70803f8045722601804f62d54c5d9d
Netbank734112 8a70801c804568ae01804f625a923f8d
尝试了这个命令,你的输入得到以下错误,我如何修改这个curl命令来得到想要的结果
result=$(curl -s -k --location --request GET "https://${HOSTNAME}/api/v1/projects/myProjects?page=1&pageSize=2" --header "Authorization: Bearer "$token"" | jq -r '["data"]|.[].unique_by(.name, .id) | map([.name, .id])[] | @tsv')
# error response
jq: error: syntax error, unexpected '(', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
["data"]|.[].unique_by(.name, .id) | map([.name, .id])[] | @tsv
jq: 1 compile error
# This one worked
result=$(curl -s -k --location --request GET "https://${HOSTNAME}/api/v1/projects/myProjects?page=1&pageSize=2" --header "Authorization: Bearer "$token"" | jq -r '.["data"]|.[]|.| .name + " " + .id')
对于.[].name + " " + .[].id'
,您在数组上迭代两次。迭代一次,一次提取数据:
curl … | jq -r '.data[] | .name + " " + .id'
Netbank734113 8a70803f8045722601804f62d54c5d9d
Netbank734112 8a70801c804568ae01804f625a923f8d
演示你可能也对使用字符串插值感兴趣:
curl … | jq -r '.data[] | "(.name) (.id)"'
演示