jq - 转换毫秒

jq - 转换毫秒

输入 json:

{
  "id": "3885",
  "login": "050111",
  "lastLoginTime": 1529730115000,
  "lastLoginFrom": "192.168.66.230"
}
{
  "id": "3898",
  "login": "050112",
  "lastLoginTime": null,
  "lastLoginFrom": null
}

当 Lastlogintime 存在时过滤器起作用:

$ jq -jr --arg ARG1 050111 'select(.login==$ARG1)|"user:", " ",.login,"\n","lastlogintime:", " ",(.lastLoginTime / 1000 | strftime("%Y-%m-%d %H:%M UTC")),"\n","lastloginfrom:", " ",.lastLoginFrom // "-","\n"' test_json3
user: 050111
lastlogintime: 2018-06-23 05:01 UTC
lastloginfrom: 192.168.66.230

但是当 lastlogintime 不存在时,就会出现问题(不打印“-”):

$ jq -jr --arg ARG1 050112 'select(.login==$ARG1)|"user:", " ",.login,"\n","lastlogintime:", " ",(.lastLoginTime / 1000 | strftime("%Y-%m-%d %H:%M UTC")),"\n","lastloginfrom:", " ",.lastLoginFrom // "-","\n"' test_json3
user: 050112
jq: error (at test_json3:12): null (null) and number (1000) cannot be divided

如何跳过最后登录时间为空的除法操作?

答案1

jq -r --arg ARG1 050112 'select(.login == $ARG1)|
    ["user:", .login],
    ["lastlogintime:", if .lastLoginTime then (.lastLoginTime/1000 | strftime("%Y-%m-%d %H:%M UTC")) else "-" end],
    ["lastloginfrom:", .lastLoginFrom // "-"]
    |@tsv' file.json

也就是说,使用显式的if- then-else表示何时lastLoginTime定义或未定义。

相关内容