skip to Main Content

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"

2

Answers


  1. You’re looking for something like this:

    .quadrants as $l | .entries[].quadrant |= . as $e | $l | index($e)
    
    Login or Signup to reply.
  2. You can also use double brackets to find the index:

    .quadrants as $q | .entries[].quadrant |= $q[[.]][]
    

    Demo

    If items in the quadrants array could occur multiple times, use first($q[[.]][]) instead.

    For large inputs with many, potentially expensive searches, you could create a lookup INDEX beforehand, and then efficiently just query that:

    (.quadrants | to_entries | INDEX(.value)) as $i | .entries[].quadrant |= $i[.].key
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search