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
You’re looking for something like this:
You can also use double brackets to find the index:
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:Demo