jsonjq

Replace a field with the index of values in an array in JQ


Given the following JSON file:

{
  "quadrants": [
    "Languages + Frameworks",
    "Tools",
    "Platforms",
    "Techniques"
  ],
  "entries": [
    {
      "quadrant": "Languages + Frameworks"
    },
    {
      "quadrant": "Platforms"
    },
    {
      "quadrant": "Languages + Frameworks"
    }
  ]
}

How can the quadrant field of each entry be replaced with the index of the corresponding value in quadrants?

Expected output:

{
  "quadrants": [
    "Languages + Frameworks",
    "Tools",
    "Platforms",
    "Techniques"
  ],
  "entries": [
    {
      "quadrant": 0
    },
    {
      "quadrant": 2
    },
    {
      "quadrant": 0
    }
  ]
}

I tried the following jq script but get null for each quadrant.

jq '
  .entries |= map(
    .quadrant = (.quadrant as $q | (.quadrants | index($q)))
  )
' "$1"

Solution

  • You're looking for something like this:

    .quadrants as $l | .entries[].quadrant |= . as $e | $l | index($e)