0

input json:

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

filter works when lastlogintime exists:

$ 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

but there is problem (does not print "-") when lastlogintime does not exist:

$ 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

how to skip divide operation for empty lastlogintimes?

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

That is, use an explicit if-then-else for when lastLoginTime is defined or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.