Home > Software design >  AWK command to read value from Json
AWK command to read value from Json

Time:05-16

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

CodePudding user response:

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

CodePudding user response:

Thank you so much for your reply. I am new to AWK. Here is the clear problem statement, below json or look like json is part of file

"[{"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"}]".

awk '/Vendor\",\"value\":\"/ {print $3}' /data/deploy.conf,

it just printing whole json again. I am not sure how to take the value out by just looking at the key.

  • Related