nobrac
nobrac

Reputation: 427

Update values in json with jq (shell script)

I am trying to update a couple values in a json array (separate file) with a shell script. Basically the logic is, set an environment variable called URL, ping that URL and add it to the json-- if 0, update another json field to SUCCESS, else update to FAILED.

Here is are the files:

info.json:

{
 "name": "PingTest",",
 "metrics": [
{
  "event_type": "PingResult",
  "provider": "test",
  "providerUrl": "URL",
  "providerResult": "RESULT"
}
]
}

pinger.sh:

#!/bin/sh

JSON=`cat info.json` #read in JSON

#Assume URL variable is set to www.dksmfdkf.com 
ping -q -c 1 "$URL" > /dev/null #ping url
if [ $? -eq 0 ]; then #if ping success, replace result in json template
  JSON=`echo ${JSON} | jq --arg v "$URL" '.metrics[].providerUrl |= $v' 
  info.json`
  JSON=`echo ${JSON} | jq '.metrics[].providerResult |= "SUCCESS"' info.json`
else
  JSON=`echo ${JSON} | jq --arg v "$URL" '.metrics[].providerUrl |= $v' 
  info.json`
  JSON=`echo ${JSON} | jq '.metrics[].providerResult |= "FAILED"' info.json`
fi

#Remove whitespace from json
JSON=`echo $JSON | tr -d ' \t\n\r\f'`

#Print the result
echo "$JSON"

The problem is my json file isn't getting updated properly, example result when running:

home:InfraPingExtension home$ ./pinger.sh
ping: cannot resolve : Unknown host
{
  "name": "PingTest",
  "metrics": [
  {
    "event_type": "PingResult",
    "provider": "test",
    "providerUrl": "",
    "providerResult": "RESULT"
  }
 ]
 }
{
  "name": "PingTest",
  "metrics": [
{
  "event_type": "PingResult",
  "provider": "test",
  "providerUrl": "URL",
  "providerResult": "FAILED"
}
  ]
}

{"name":"PingTest","metrics":[{"event_type":"PingResult","provider":"test","providerUrl":"URL","providerResult":"RESULT"}]}

Upvotes: 1

Views: 4032

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295520

This would be greatly simplified by only calling jq once.

host=${URL#http://}; host=${host#https://}; host=${host%%/*}
if ping -q -c 1 "$host"; then
  result=SUCCESS
else
  result=FAILED
fi

JSON=$(
  jq -c \
     --arg url "$URL" \
     --arg result "$result" \
     '.metrics[].providerUrl |= $url
      | .metrics[].providerResult |= $result
  ' info.json
)

Upvotes: 3

Related Questions