0

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 pretty printed?

Edit:

OK, I can use jq but I want to solve this just with grep and regex.

halfer
  • 19,824
  • 17
  • 99
  • 186
hiaclibe
  • 636
  • 9
  • 25
  • 1
    There are multiple issues possible. Do check http://shellcheck.net – anishsane Aug 02 '16 at 10:00
  • 1
    In [Merge two json in bash (no jq)](http://stackoverflow.com/q/38659763/) you can read some interesting comments on why it is not a good idea to try to parse JSON with Bash instead of using the tool for it (jq). – fedorqui Aug 02 '16 at 10:17

1 Answers1

1

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

O/P:

"field1":"field1Value"
"field2":"field2Value"
jijinp
  • 2,592
  • 1
  • 13
  • 15