API JSON从bash获取ID

时间:2017-04-07 04:37:54

标签: json bash curl

只是想知道是否有人可以帮助我获得" SNAPSHOTID"从输出以下输出的CURL命令输出的第一条记录?我试过JQ,但我得到了

  

"解析错误:第1行第6列和第34行的数字文字无效;

还有其他想法吗?

{  
   "9875a8e4fc31f3":{  
      "SNAPSHOTID":"98758e4afc31f3",
      "date_created":"2017-04-05 10:16:17",
      "description":"centminmod",
      "size":"42949672960",
      "status":"complete"
   },
   "b0d58e5b0d46e":{  
      "SNAPSHOTID":"b0d58e5b0d46e",
      "date_created":"2017-04-05 23:07:00",
      "description":"serverpilot",
      "size":"42949672960",
      "status":"complete"
   },
   "d3158e6fbaa204":{  
      "SNAPSHOTID":"d3a158e6fba204",
      "date_created":"2017-04-06 22:38:26",
      "description":"",
      "size":"42949672960",
      "status":"complete"
   },
   "39a58ae6fe12f0":{  
      "SNAPSHOTID":"39aa58e6fe1a2f0",
      "date_created":"2017-04-06 22:48:50",
      "description":"",
      "size":"42949672960",
      "status":"complete"
   },
   "51458ea70124c7":{  
      "SNAPSHOTID":"514a58e701a24c7",
      "date_created":"2017-04-06 23:01:56",
      "description":"",
      "size":"42949672960",
      "status":"complete"
   },
   "b2a58e7a04af99":{  
      "SNAPSHOTID":"b2a5a8e70a4af99",
      "date_created":"2017-04-06 23:17:03",
      "description":"",
      "size":"42949672960",
      "status":"complete"
   },
   "17b58e70a7133c":{  
      "SNAPSHOTID":"17b58ae7a07133c",
      "date_created":"2017-04-06 23:27:15",
      "description":"",
      "size":"42949672960",
      "status":"complete"
   },
   "32958e70aa0acf":{  
      "SNAPSHOTID":"32958eaa70a0acf",
      "date_created":"2017-04-06 23:39:54",
      "description":"",
      "size":"42949672960",
      "status":"complete"
   },
   "dfa58e70d63a57":{  
      "SNAPSHOTID":"dfa58ea70d6357",
      "date_created":"2017-04-06 23:54:11",
      "description":"",
      "size":"42949672960",
      "status":"complete"
   },
   "96358e712bf80":{  
      "SNAPSHOTID":"96358e7a12bf80",
      "date_created":"2017-04-07 00:17:03",
      "description":"",
      "size":"0",
      "status":"pending"
   }
}

3 个答案:

答案 0 :(得分:1)

可能有点过于复杂但有效:

grep SNAPSHOTID | head -n 1 | sed "s/[^\"']*.SNAPSHOTID.[^\"']*.\([^\"']*\).*/\1/"

答案 1 :(得分:1)

如果你包装了' SNAPSHOTID'进入一个数组然后你可以像这样提取它

curl --silent http://url.to.json | jq '[.[].SNAPSHOTID] | .[0]'

man curl

取得的--silent开关
  

-s, - silent       无声或安静模式。不要显示进度表或错误消息。       使卷曲静音。它仍会输出您要求的数据,甚至可能输出到终端/标准输出,除非您重定向它。

答案 2 :(得分:0)

我会选择to_entries,然后生成一个数组,可以直接索引你想要的部分,例如:

<test.json jq 'to_entries | first | .value.SNAPSHOTID'

输出:

"98758e4afc31f3"