Home > database >  Find all matching values in a JSON object whose corresponding keys are regex and match a provided st
Find all matching values in a JSON object whose corresponding keys are regex and match a provided st

Time:12-31

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.

CodePudding user response:

Here is how you do it in JQ:

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

Online demo

CodePudding user response:

$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
  • Related