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

Select objects based on the key in hash using jq

I’d love to select objects based on the key in the hash, but I want the original object format back. How can I achieve this?

original

{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  },
  "aaa.com": {
    "https": {
      "dest_url": "https://github.com"
    }
  },
  "bbb.com": {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  },
   "ccc.com": {
    "https": {
      "dest_url": "https://.com"
    }
  }
}

should be

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

{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  },
  "bbb.com": {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  }
}

I tried it with to_entries[] | select (.key == "google.com" or .key == "bbb.com") | [.key, .value] but it eneded like this. I’m sure [.key, .value] part is wrong but I’m stuck on how I can workaround this.

[
  "google.com",
  {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  }
]
[
  "bbb.com",
  {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  }
]

>Solution :

Use with_entries(…), which is a shortcut to to_entries | map(…) | from_entries, which in turn decomposes the object into an array of key/value representations to_entries, modifies each item within that array map, and converts it back into the original structure from_entries.

jq 'with_entries(select(.key == "google.com" or .key == "bbb.com"))'
{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  },
  "bbb.com": {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  }
}

Demo

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