使用jq(shell脚本)更新json中的值

时间:2018-01-29 16:06:32

标签: json bash shell jq

我正在尝试使用shell脚本更新json数组(单独文件)中的几个值。基本上逻辑是,设置一个名为URL的环境变量,ping该URL并将其添加到json--如果为0,则将另一个json字段更新为SUCCESS,否则更新为FAILED。

以下是文件:

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"

问题是我的json文件没有正确更新,运行时的示例结果:

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"}]}

1 个答案:

答案 0 :(得分:2)

只需拨打jq 一次即可大大简化。

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[].providerUrl |= $result
  ' info.json
)