使用jq或grep将json输出键值卷曲到变量

时间:2019-09-30 07:04:51

标签: json jq

我已经将curl json输出存储到一个变量中。而且我只想检索描述并将其存储在另一个变量中。

我尝试了jq和grep,但是没有用。

var=`curl -i -X POST -H 'Content-Type: application/json' -d '
{
    "jsonrpc": "2.0",
    "method": "trigger.get",
    "params": {
        "filter": {"value": "1"},
        "sortfield": "lastchange",
        "limit": 20
    },
    "auth": "authstring",
    "id": 1
}' http://127.0.0.1/zabbix/api_jsonrpc.php`


echo $var

{
   "jsonrpc":"2.0",
   "result":[
      {
         "triggerid":"17169",
         "expression":"{19444}=1",
         "description":"Zabbix agent on {HOST.NAME} is unreachable for 5 minutes",
         "url":"",
         "status":"0",
         "value":"1",
         "priority":"3",
         "lastchange":"1569589239",
         "comments":"",
         "error":"",
         "templateid":"13437",
         "type":"0",
         "state":"0",
         "flags":"0",
         "recovery_mode":"0",
         "recovery_expression":"",
         "correlation_mode":"0",
         "correlation_tag":"",
         "manual_close":"0",
         "details":""
      },
      {
         "triggerid":"18123",
         "expression":"{20525}=1",
         "description":"Zabbix agent on {HOST.NAME} is unreachable for 5 minutes",
         "url":"",
         "status":"0",
         "value":"1",
         "priority":"3",
         "lastchange":"1569590703",
         "comments":"",
         "error":"",
         "templateid":"13437",
         "type":"0",
         "state":"0",
         "flags":"0",
         "recovery_mode":"0",
         "recovery_expression":"",
         "correlation_mode":"0",
         "correlation_tag":"",
         "manual_close":"0",
         "details":""
      }
   ],
   "id":1
}

echo $var | jq -r '.description'
  

解析错误:第1行第9列的数字文字无效

知道这个错误是什么意思吗?另外我怎么能用grep实现呢?

弄清楚如何使用grep执行此操作。因此,现在我只需要弄清楚jq错误的含义以及纠正方法。

echo $var | grep -Po '"description":.*?[^\\]",'
"description":"Zabbix agent on {HOST.NAME} is unreachable for 5 minutes",
"description":"Zabbix agent on {HOST.NAME} is unreachable for 5 minutes",

2 个答案:

答案 0 :(得分:0)

使用jq,您基本上有两种选择:

echo $var | jq '.. | .description?'

或者如果您想更具体一点:

echo $var | jq '.result[] | .description?'

但是还有其他变化...

答案 1 :(得分:0)

您的$var标准输出可能没有正确的json格式,请首先验证您的$varhttps://jsonlint.com/

然后重试以下内容:

echo $var | jq '.result[].description'