5
function getVal {
  sedPattern='s/^.*"keyVal":"\([^"]*\)".*$/\1/'
  finalSedPattern=${sedPattern/keyVal/$2}
  echo $(sed $finalSedPattern  <<< $1)
}

This is my Json parser written using sed. It takes json string, key name and returns the value like,

myJson='{"hello":"sk"}'
val=$(getVal $myJson hello)
echo $val

prints, sk

But sometimes, my json string may or may not contain space as,

myJson='{"hello" : "sk"}'

In that case, the function fails. I tried with tweaking the above pattern by adding [ ] to match zero or more spaces as,

sedPattern='s/^.*"keyVal"[ ]+:"\([^"]*\)".*$/\1/'

It throws error as,

unterminated `s' command

How can i give non-capturing pattern groups inside sed?

0

2 Answers 2

6

Your sedPattern has some issue with quotes. you are trying to match the same quote twice. Also, + is used for one or more. for 0 or more, use *.
caution: code below is untested, but should get you going.

sedPattern='s/^.*"keyVal"[ ]*:.*\(".*"\).*$/\1/'

0

You should quote variable expansions (just one example from your code):

sed $finalSedPattern

is unquoted and will be split on spaces (when used). You should use:

sed "$finalSedPattern"

Your function with quotes:

function getVal {  
    sedPattern='s/^.*"keyVal":"\([^"]*\)".*$/\1/1'
    finalSedPattern="${sedPattern/keyVal/$2}"
    echo "$(sed "$finalSedPattern"  <<< "$1")"
}

And with optional spaces:

function getVal {
    sedPattern='s/^.*"keyVal"[ ]\{0,\}:[ ]\{0,\}"\([^"]*\)".*$/\1/1'
    finalSedPattern="${sedPattern/keyVal/$2}"
    echo "$(sed "$finalSedPattern"  <<< "$1")"
}

You must log in to answer this question.