【问题标题】:How to to extract the year from JSON date using jq如何使用 jq 从 JSON 日期中提取年份
【发布时间】:2021-02-02 15:50:13
【问题描述】:

我有一堆带有 ISO 格式日期的 JSON。如何只打印日期的年份部分?

$ echo '{"createdDate": "2005-09-28T16:34:40Z"}' | jq '{ createdYear: ??? }'
{
  "createdYear": "2005"
}

【问题讨论】:

    标签: json command-line jq


    【解决方案1】:

    为什么不只是:

    {createdYear: .createdDate[0:4]}
    

    【讨论】:

      【解决方案2】:

      使用strptime 将日期字符串转换为日期对象,然后使用strftime 格式化日期:

      $ echo '{"createdDate": "2005-09-28T16:34:40Z"}' |
          jq '
             { createdYear: .createdDate
                 | strptime("%Y-%m-%dT%H:%M:%SZ")
                 | strftime("%Y") }'
      {
        "createdYear": "2005"
      }
      

      【讨论】:

        猜你喜欢
        • 2016-08-02
        • 1970-01-01
        • 1970-01-01
        • 2021-04-02
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多