Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do we need map function in jq?

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"))'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading