Using jq to extract specific property values and output on a single line

≯℡__Kan透↙ 提交于 2020-03-21 14:32:14

问题


I've this ElasticSearch snapshot output and would like to reduce it to print, on a single line, from each snapshot the values of the end_time_in_millis and snapshot property separate by a space:

1429609790767 snapshot_1
1429681169896 snapshot_2

Basically the output of

  • cat data | jq '.snapshots[].end_time_in_millis' and
  • cat data | jq '.snapshots[].snapshot'

but combined on one line.

I was looking at map but couldn't make out how to apply it; also reading this answer I tried:

cat data  | jq '.snapshots[] | map(. |= with_entries( select( .key == ( "snapshot") ) ) )'

But that produces lots of errors and null output.

The data:

{
  "snapshots": [
    {
      "shards": {
        "successful": 1,
        "failed": 0,
        "total": 1
      },
      "failures": [],
      "snapshot": "snapshot_1",
      "indices": [
        "myindex1"
      ],
      "state": "SUCCESS",
      "start_time": "2015-04-21T09:45:47.041Z",
      "start_time_in_millis": 1429609547041,
      "end_time": "2015-04-21T09:49:50.767Z",
      "end_time_in_millis": 1429609790767,
      "duration_in_millis": 243726
    },
    {
      "shards": {
        "successful": 1,
        "failed": 0,
        "total": 1
      },
      "failures": [],
      "snapshot": "snapshot_2",
      "indices": [
        "myindex1"
      ],
      "state": "SUCCESS",
      "start_time": "2015-04-22T05:36:02.333Z",
      "start_time_in_millis": 1429680962333,
      "end_time": "2015-04-22T05:39:29.896Z",
      "end_time_in_millis": 1429681169896,
      "duration_in_millis": 207563
    }
  ]
}

回答1:


Use this filter:

.snapshots[] | "\(.end_time_in_millis) \(.snapshot)"

This builds up a string for each of the snapshots consisting of the end time and the snapshot name.

Just make sure you use the -r option to get the raw output.



来源:https://stackoverflow.com/questions/29982897/using-jq-to-extract-specific-property-values-and-output-on-a-single-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!