26

input json:

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

I want to get output for login, lastLoginTime and lastLoginFrom in tabulator delimited format:

050111  1529730115000   192.168.66.230
050112              -                -

with below jq filter I get on output no "null" values which I could replace with "-"

$ jq -r '.|[.login, .lastLoginTime, .lastLoginFrom]|@tsv' test_json
050111  1529730115000   192.168.66.230
050112

Is there any other way to get "-" printed for such null values?

Chris
  • 3,591
  • 7
  • 24
  • 35

2 Answers2

52

use the alternative operator: //

so :

$jq -r '.|[.login, .lastLoginTime // "-" , .lastLoginFrom // "-" ]|@tsv' test_json
050111  1529730115000   192.168.66.230
050112  -   -
aymericbeaumet
  • 103
  • 1
  • 4
EchoMike444
  • 3,045
  • 1
  • 11
  • 14
2

This is using the same actual feature of jq to change the null values into dashes as EchoMike444 in their answer, but doing it in another way.

Instead of listing the keys to extract, I delete the id key that we don't want to use. I then extract the remaining values and use map() to change the values that are null into dashes:

$ jq -r '[del(.id)[]] | map(.//"-") | @tsv' file
050111  1529730115000   192.168.66.230
050112  -       -

Using Miller (mlr) to read the JSON input and change all fields that are null to -. We then exclude the id field and output what's left as TSV.

$ mlr --ijson --otsv --headerless-csv-output put 'for (k,v in $*) { is_null(v) { $[k] = "-" } }' then  cut -x -f id file
050111  1529730115000   192.168.66.230
050112  -       -
Kusalananda
  • 320,670
  • 36
  • 633
  • 936