Search code examples
jsonjqdistinct-values

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"]

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"
    ]