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
$arg
is the string which you pass to the script, andrules.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.Here is how you do it in JQ:
Online demo