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: check if substring from key exists in an array

I have an array of objects as input, each object looking as follows:

{
  "downloadDir": "/merge/downloads",
  "id": 2485,
  "labels": [
    "irrelevant",
    "downloads"
  ]
}

I am trying to have JQ go through every object and find those, which do not have an element in the .labels array that is a substring of .downloadDir between 1st and 2nd ‘/’, i.e.

  • for "/merge/downloads" it should be "downloads"
  • for "/merge/tv/downloads" it should be "tv"
  • for "/merge/tv-share/downloads" it should be "tv-share"

For matching objects it should return their .id.

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

Having reviewed some similar questions on Stack Overflow, I’m thinking the logic is supposed to look something like this: map(select(.labels | index(.downloadDir))). This works if I have a static string in index(), like map(select(.labels | index("downloads"))), however I can’t get it to work with .downloadDir: it throws out "Cannot index array with string "downloadDir"" or "Cannot index string with string "labels"", depending on whether I pass the input as an array or not.

I am entirely unsure how to approach applying a regex to .downloadDir to grab the needed substring from it.

>Solution :

Split the .downloadDir at "/" using /, and take the second item. Compare it to each item in .labels and yield true if at least one (any) matches. select those items, and output the .id.

jq 'select(any(.labels[] == (.downloadDir / "/")[2]; .)).id ' input.json
2485

Demo

This works on a stream of items (as suggested by your sample). If your input is indeed an array of items, prepend .[].

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