2

I have a JSON file:

[
  {
    "platform": "p1",
    "id": "5",
    "pri": "0",
    "sec": "20"
  }
]
[
  {
    "platform": "p2",
    "id": "6",
    "pri": "10",
    "sec": "0"
  }
]

I can to format it to the form:

$ jq -c '.[]|{PLATFORM: .platform, ID: .id, PRI: .pri, SEC: .sec}' test.json
{"PLATFORM":"p1","ID":"5","PRI":"0","SEC":"20"}
{"PLATFORM":"p2","ID":"6","PRI":"10","SEC":"0"}
$

but how to ignore SEC/PRI with "0" and get output in form:

PLATFORM:p1, ID:5, SEC:20
PLATFORM:p2, ID:6, PRI:10

I can process it with bash/awk command, but maybe someone have a solution with jq directly.

thank you,

2 Answers2

2

You can use conditional statements to remove the unwanted keys, e.g.:

if (.sec == "0") then del(.sec) else . end

The formatting could be done with @tsv by converting the data to an array, e.g.:

filter.jq

.[]                                        | 
if (.sec == "0") then del(.sec) else . end | 
if (.pri == "0") then del(.pri) else . end | 
to_entries                                 |
map("\(.key | ascii_upcase):\(.value)")    |
@tsv

Run it like this:

jq -crf filter.jq test.json

Output:

PLATFORM:p1 ID:5    SEC:20
PLATFORM:p2 ID:6    PRI:10
peak
  • 105,803
  • 17
  • 152
  • 177
Thor
  • 45,082
  • 11
  • 119
  • 130
0

jq solution:

jq -c 'def del_empty($k): if (.[$k]|tonumber > 0) then . else del(.[$k]) end;
      .[] | {PLATFORM: .platform, ID: .id, PRI: .pri, SEC: .sec}
      | del_empty("PRI")
      | del_empty("SEC")' test.json

The output:

{"PLATFORM":"p1","ID":"5","SEC":"20"}
{"PLATFORM":"p2","ID":"6","PRI":"10"}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105