Is there a way of extracting portion of a key value between delimiters?

67 views Asked by At

Here is my JSON. Its in a file called file1.txt

{
    "foo": [
        {
            "bar": {
                "second": {
                    "key1": "some/path/to/delimiter1_FIRST_IMPORTANT_VALUE_delimter2",
                    "key2": "OK_as_it_is",
                    "key3": "Just to show there is more stuff"
                }
            }
        },
        {
            "bar": {
                "second": {
                    "key1": "some/path/to/delimiter1_SECOND_IMPORTANT_VALUE_delimter2",
                    "key2": "Also_OK_as_it_is",
                    "key3": "Just to show there is more stuff"
                }
            }
        }
    ]
}

What I want to do is extract PORTION of the key1 value - the bits between delimiter1 and delimiter2 which would be _FIRST_IMPORTANT_VALUE_ and _SECOND_IMPORTANT_VALUE_

I know that the following ALMOST works:

$ cat file1.txt | jq '.foo[].bar.second | (.key1[23:46]),  .key2'
"_FIRST_IMPORTANT_VALUE_"
"OK_as_it_is"
"_SECOND_IMPORTANT_VALUE"
"Also_OK_as_it_is"

...but as you can see, it misses the last character of _SECOND_IMPORTANT_VALUE_

So I need a more generalised form of the jq '.foo[].bar.second | (.key1[23:46]), .key2' that replaces the numbers 23 and 46 with values determined from delimiter1 and delimiter2

I really want to keep it to a single line - without using bash variables over multiple lines, sort of keep it within jq.

2

There are 2 answers

0
oguz ismail On BEST ANSWER

Using a regex:

.foo[].bar.second
| (.key1 | capture("delimiter1(?<v>.*)delimter2").v)
, .key2

Online demo

2
danimacs On

You can do it using a regex:

cat file1.txt | jq '.foo[].bar.second | (.key1 | match("delimiter1([^*]*)delimter2").captures[0].string), .key2'