jq json解析 - 使用todate替换时间戳到日期,并展平数组

时间:2016-12-19 12:10:25

标签: json bash parsing aws-cli jq

2个问题:

1)我想保持json不变,但将时间戳更改为人类可读日期,如“2016-12-19T09:21:35Z”

{
  "Action": "ALLOW",
  "Timestamp": 1482139256.274,
  "Request": {
    "Country": "US",
    "URI": "/version/moot/beta.json",
    "Headers": [
      {
        "Name": "Host",
        "Value": "static.tiza.com"
      },
      {
        "Name": "User-Agent",
        "Value": "Faraday v0.9.2"
      },
      {
        "Name": "Accept-Encoding",
        "Value": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
      },
      {
        "Name": "Accept",
        "Value": "*/*"
      },
      {
        "Name": "X-Newrelic-Id",
        "Value": "Vgcs5gbFU123dFBWGwIdAVFdrXBwc="
      },
      {
        "Name": "X-Newrelic-Transaction",
        "Value": "PxQDQVlzZVUd3NKQcrEwWwU"
      }
    ],
    "ClientIP": "107.22.17.51",
    "Method": "GET",
    "HTTPVersion": "HTTP/1.1"
  },
  "Weight": 1
}

我知道我可以使用'todate'jq功能,但我丢失了所有其他数据

sh# cat temp.json | jq -r '.SampledRequests[].Timestamp | todate'
2016-12-19T09:21:44Z

---------更新了--------

第二个问题: 2)如何从“Request {}”级别的数组中取出.Headers []的内容。

从:

{
  "TimeWindow": {
    "EndTime": 1482156660,
    "StartTime": 1482156420
  },
  "SampledRequests": [
    {
      "Action": "ALLOW",
      "Timestamp": 1482139256.274,
      "Request": {
        "Country": "US",
        "URI": "/version/moot/beta.json",
        "Headers": [
          {
            "Name": "Host",
            "Value": "static.tiza.com"
          },
          {
            "Name": "X-Newrelic-Transaction",
            "Value": "PxQDQVlzZVUd3NKQcrEwWwU"
          }
        ],
        "ClientIP": "107.22.17.51",
        "Method": "GET",
        "HTTPVersion": "HTTP/1.1"
      },
      "Weight": 1
    }
  ],
  "PopulationSize": 89
}

要:

{
    "TimeWindow.EndTime": 1482156660,
    "TimeWindow.StartTime": 1482156420,
    "Action": "ALLOW",
    "Timestamp": 1482139256.274,
    "Request.Country": "US",
    "Request.URI": "/version/moot/beta.json",
    "Headers.Host": "static.tiza.com",
    "Headers.X-Newrelic-Transaction": "PxQDQVlzZVUd3NKQcrEwWwU",
    "ClientIP": "107.22.17.51",
    "Method": "GET",
    "HTTPVersion": "HTTP/1.1",
    "Weight": 1,
    "PopulationSize": 89
}

非常感谢,

摩西

1 个答案:

答案 0 :(得分:1)

1)使用| =而不仅仅是|

2)转换片段的一种方法:

{
  "Headers": [
    {
      "Name": "Host",
      "Value": "static.tiza.com"
    },
    {
      "Name": "User-Agent",
      "Value": "Faraday v0.9.2"
    }
  ]
}

根据需要使用过滤器:

.Headers[] | { ("Headers." + .Name): .Value }

在您的情况下,您可以使用以下过滤器(2):

.SampledRequests[].Request.Headers[] |=
    { ("Headers." + .Name): .Value }

我会把它留给你把所有碎片放在一起: - )