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

How to flatten array of objects in jq

I have an array of objects in a json file:

{
  "Items": [
    {
      "LOCATION": {
        "NAME": "Dallas"
      }
    },
    {
      "LOCATION": {
        "NAME": "New York"
      }
    },
    {
      "LOCATION": {
        "NAME": "Dallas"
      }
    }
  ]
}

I want to to iterate over the objects and get a unique list of names.

In this example, the desired output would be ["Dallas", "New York"]

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

How do I do this? I have tried the following but it fails:

jq '.Items | map({LOCATION}) | .unique_by(.NAME)' file.json

>Solution :

unique_by lets you obtain higher-level items (the objects in this case) staisfying a lower-level condition (uniqueness in this case). But you only want the unique array itself, so unique already does the job:

jq '.Items | map(.LOCATION.NAME) | unique'
[
  "Dallas",
  "New York"
]
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