从 curl API 请求解析 JSON 数据

Rya*_*n R 2 curl json jq

我正在使用 Shodan 的 API https://developer.shodan.io/api来获取我当前的网络警报。我想用 jq 解析出警报的 id。

卷曲请求是 curl -X GET -i https://api.shodan.io/shodan/alert/info?key={API KEY}

该请求的输出是格式如下的 json 数据:

[
 {
  "name": "Test Alert",
  "created": "2017-01-09T21:53:17.104000",
  "expires": 0,
  "expiration": null,
  "filters": {
   "ip": [
    "198.20.88.870"
   ]
  },
  "id": "HKVGCP1WD79Z7W2T",
  "size": 1
 }
]
Run Code Online (Sandbox Code Playgroud)

使用curl -X GET -i https://api.shodan.io/shodan/alert/info?key={API KEY} | jq '.id'给出以下错误:

"parse error: Invalid numeric literal at line 1, column 9"
Run Code Online (Sandbox Code Playgroud)

jes*_*e_b 8

-i选项意味着 curl 将包含非 JSON 格式的 http 响应标头。这就是导致解析错误的原因,但是鉴于您提供的 json,您需要使用[]它来告诉它迭代数组:

curl 'https://api.shodan.io/shodan/alert/info?key={API KEY}' | jq '.[].id'
Run Code Online (Sandbox Code Playgroud)

或者(和 IMO 更直观)使用json

curl 'https://api.shodan.io/shodan/alert/info?key={API KEY}' | json -a id
Run Code Online (Sandbox Code Playgroud)

此外 json(1) 可以-H选择忽略 http 响应标头,因此您可以使用json -Ha id