'AWK command to read value from Json
I want to read a value using awk command from below json by giving the key name as input, can you please help me on this
"[{\"key\":\"ResourceClass\",\"value\":\"SingleNode\"},{\"key\":\"Vendor\",\"value\":\"AWS\"},{\"key\":\"Creator\",\"value\":\"ea35b938-c575-41d3-8705\"},{\"key\":\"ClusterName\",\"value\":\"cluster-Offer\"},{\"key\":\"ClusterId\",\"value\":\"056-987-656\"},{\"key\":\"JobId\",\"value\":\"1323\"},{\"key\":\"RunName\",\"value\":\"OfferDataProcess\"}]"
Expected output for a given key
"RunName"
OfferDataProcess
Solution 1:[1]
Welcome to SO. You are recommended here to make an efford to show what you have tried, then post your specific problems. Not just state "help me do this". Please see how to ask a good question
Your source is not correct JSON, so your question is unclear. Do you actually HAVE json, or is the string the quoted json, to get a json ?
In any case, since AWK does not understand json, you too should stop seeing json as that. See it as a string.
Something like this will get the disired result for the specific example
BEGIN{
FS="{"
key="RunName"
}
{
for (i=1; i<=NF; i++){
if ($i~key) {
mykey=$i
# ----- first variant ------ correct json
# match on "value":"mystringhere"
c=match(mykey, /"value":"([^"]*)/, arr)
if (c>1){
print "\""key"\""
print arr[1]
}
# ----- second variant ----- quoted json
# match on \"value\":\"mystringhere\"
c=match(mykey, /\\"value\\":\\"([^\\]*)/, aq)
if (c>1){
print "\""key"\""
print aq[1]
}
} # if
} #forloop
} #actions
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MyICQ |
