skip to Main Content

I have a json string of the following type

{
  "[A-Z]+": {
    "k": "test1", 
    "c": "stg1"
  }, 
  "[a-z]+": {
    "k": "test2", 
    "c": "stg2"
  }
}

The objective is that given a string, if this string matches the regex pattern of one of the keys, then return the value stored in the k field of the first matching object. I am looking for a solution in bash.

For example, if I have the string MAIN, then this script should return test1 because the given string matches the pattern in the key of the first object.

I tried using jq but it seems to be doing the opposite of what I am trying to achieve. The match function accepts a regex and I am able to get all keys in the json that matches this regex. But in my case, the regex pattern is in the json and the string is the argument.

2

Answers


  1. $arg is the string which you pass to the script, and rules.json is where your rule is stored.

    The script extracts all keys from the JSON file and test them against the argument. Once the expected key is found, the script call jq again to get the value.

    for pat in $(cat rules.json |jq 'keys_unsorted[]'); do 
      [[ $arg =~ $(echo $pat | jq -r '.') ]] && cat rules.json | jq -r ".[$pat].k" && break; 
    done
    
    Login or Signup to reply.
  2. Here is how you do it in JQ:

    first(.[keys_unsorted[] | select(. as $re | "MAIN" | test($re))].k)
    

    Online demo

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