I am just playing with jq. Please check the following outputs.
% FRUITS='[
{
"name": "apple",
"color": "green",
"price": 1.2
},
{
"name": "banana",
"color": "yellow",
"price": 0.5
},
{
"name": "kiwi",
"color": "green",
"price": 1.25
}
]'
% echo $FRUITS
% echo $FRUITS | jq .
% echo $FRUITS | jq '[.[].color] | unique'
[
"green",
"yellow"
]
% echo $FRUITS | jq 'map(.color) | unique'
[
"green",
"yellow"
]
% echo $FRUITS | jq '. | map(has("name"))'
[
true,
true,
true
]
% echo $FRUITS | jq '[.[] | has("name")]'
[
true,
true,
true
]
Here, jq '[.[].color] | unique' give the same output as jq 'map(.color) | unique'
jq '[.[] | has("name")]' give the same output as jq '. | map(has("name"))'
I am not understanding what is the purpose and difference of the map function.
>Solution :
The map function leaves the array intact while .[] splits the array. Often times they return the same result but in specific use cases they will perform differently.
More info can be found in the answers to this question:
JQ map objects to array