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

Searching through an array

Trying to learn how to think in jq script.

Given this data:

{
   "characters": [
       { "First": "Fred", "Last": "Weasley" },
       { "First": "George", "Last": "Weasley" },
       { "First": "Hermione", "Last": "Granger" },
       { "First": "Ron", "Last": "Weasley" },
       { "First": "Hagrid" },
       { "First": "Draco", "Last": "Malfoy" },
       { "First": "Molly", "Last": "Weasley" },
       { "First": "Voldemort" },
       { "First": "Lucius", "Last": "Malfoy" }
    ]
}

Find all characters with the same last name as "Ron". And no, you don’t already know his last 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

>Solution :

Find the last name you are looking for and save it in a variable, then update the characters array accordingly:

jq '
  (.characters[] | select(.First == "Ron").Last) as $last
  | .characters |= map(select(.Last == $last))
'
{
  "characters": [
    {
      "First": "Fred",
      "Last": "Weasley"
    },
    {
      "First": "George",
      "Last": "Weasley"
    },
    {
      "First": "Ron",
      "Last": "Weasley"
    },
    {
      "First": "Molly",
      "Last": "Weasley"
    }
  ]
}

Demo


If you want to make the call with a dynamic first name, provide it using a parameter variable:

jq --arg first "Ron" '
  (.characters[] | select(.First == $first).Last) as $last
  | .characters |= map(select(.Last == $last))
'
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