Home > database >  Searching through an array
Searching through an array

Time:02-19

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.

CodePudding user response:

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

CodePudding user response:

You have an array of objects called "characters" each containing a "first" and "last" variable. Now to get the first one. Go characters[0].first which would return. "Fred" Or characters.[3].last would return "Weasley" Note the first entry in array is fetched by index 0. Make sense?

  • Related