user6270875 user6270875 - 4 months ago 11
JSON Question

Bash function: extraxt different fields from json with grep regex

How can I write a bash function to extract a user defined field from json?

#!/bin/bash
JSON='{"field1":"field1Value","field2":"field2Value"}'
function getFieldValueFromJson {
JSON_FIELD=$1
JSON=$2
regex=".\"$JSON_FIELD\":\".*\""
key=$(echo $JSON |grep -Po $regex)
echo $key
}
getFieldValueFromJson field1 $JSON
getFieldValueFromJson field2 $JSON


Output is:


{"field1":"field1Value","field2":"field2Value"

,"field2":"field2Value"


Any idea how to solve this problem, if JSON is never pritty printed?

Info: Ok I can use jq but I want to solve this just with grep & regex.

Answer

With regex="\"$JSON_FIELD\":\"[^(\",)]*\""

O/P:

"field1":"field1Value"
"field2":"field2Value"