how to get multiple values from a JSON array/object using jq in a single line?
here curl request and its response
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",
}
]
Now try the below command to get the id and name in one line but duplicate results are coming.
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
how do I get rid of those duplicated values and basically get the below response?
Netbank734113 8a70803f8045722601804f62d54c5d9d
Netbank734112 8a70801c804568ae01804f625a923f8d
Tried this command with your inputs getting the below errors, how do I modify this curl command to get desired results.
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')
CodePudding user response:
With .[].name " " .[].id'
you iterate twice over the array. Iterate once and extract your data in one go:
curl … | jq -r '.data[] | .name " " .id'
Netbank734113 8a70803f8045722601804f62d54c5d9d
Netbank734112 8a70801c804568ae01804f625a923f8d
You might also be interested in using string interpolation:
curl … | jq -r '.data[] | "\(.name) \(.id)"'