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

jq: replace a field with the index of values in an array

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:

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

{
  "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)
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