首页 > 解决方案 > 如何使用 jq 将 JSON 中的 ISO 时间戳字段转换为纪元

问题描述

我有一组这样的 JSON 消息:

{
  "type": "Point",
  "time": "2021-04-01T01:19:21.243866342Z",
  "value": 1,
  "metric": "iterations",
  "method": "",
  "name": "",
  "proto": "",
  "status": "",
  "tls_version": "",
  "url": "",
  "expected_response": "",
  "group": "",
  "scenario": "default",
  "agent_hostname": "ip-13-3-3-33.ap-southeast-2.compute.internal",
  "agent_ipaddress": "33.3.3.3",
  "agent_casetype": "simplerequest",
  "agent_casename": "test_case"
}

这是由应用程序生成并存储在文件夹中的消息。我想将时间字段从 ISO 转换为纪元微秒。

我可以使用这个:.time_field | .[0:-9] | strptime("%Y-%m-%dT%H:%M:%S") | 时间

但这删除了整个小数部分,只给了我第二个粒度。这是趋势数据,可能会在同一秒内发生一些事件。

我怎样才能使用 jq 来实现呢?

谢谢

标签: jsontimestampjq

解决方案


您对仅使用整数秒的时间函数是正确的。这个答案使用字符串函数来解析分数。

如果这是file.json包含一个对象数组

[
    {
        "type": "Point",
        "time": "2021-04-01T01:19:21.243866342Z"
    },
    {
        "type": "Circle",
        "time": "2020-01-01T00:00:00.01Z"
    },
    {
        "type": "Line",
        "time": "1970-01-01T01:00:00Z"
    }
]

然后

jq '
    def datestamp2epoch:
        . | scan("(.+?)([.][0-9]+)?Z$")
          | [(.[0] + "Z" | fromdateiso8601), (.[1] // 0 | tonumber)]
          | add;
    map(.time |= datestamp2epoch)
' file.json
[
  {
    "type": "Point",
    "time": 1617243561.2438664
  },
  {
    "type": "Circle",
    "time": 1577836800.01
  },
  {
    "type": "Line",
    "time": 3600
  }
]

推荐阅读