Home > Blockchain >  Display row when field value is absent
Display row when field value is absent

Time:04-12

This bash one-liner is working great.

curl https://MyUrl | jq -cr '.[] | {id: .id, completed: .completed, content: .content | sub(","; "") , assignee: .assignees[] | objects | .name} '

The output:

{"id":4799371614,"completed":false,"content":"todo item A","assignee":"Goofy"}
{"id":4799371614,"completed":false,"content":"todo item B","assignee":"Donald Duck"}
{"id":4799371930,"completed":false,"content":"todo item C","assignee":"Mickey"}
{"id":4799371981,"completed":false,"content":"todo item D","assignee":"Mickey"}

Almost perfect! But, there are actually 9 rows. It just happens that the 4 entries above have the .assignees array.

Is there a way I can return rows, even if .assignees is empty? Perhaps output a "-" or "empty" value?

Example output if I remove the .assignees filter:

{"id":4799371614,"completed":false,"content":"todo item A"}
{"id":4799371614,"completed":false,"content":"todo item B"}
{"id":4799371930,"completed":false,"content":"todo item C"}
{"id":4799371981,"completed":false,"content":"todo item D"}
{"id":5799371614,"completed":false,"content":"todo item E"}
{"id":6799371614,"completed":false,"content":"todo item F"}
{"id":7799371930,"completed":false,"content":"todo item G"}
{"id":8799371981,"completed":false,"content":"todo item H"}
{"id":9799371981,"completed":false,"content":"todo item I"}

That is, E-I do not have .assignees, so they are not part of the first jq output, but they are part of the first.

CodePudding user response:

You can use the alternative operator //, and you parentheses to create 'temporary' values:

echo '[{"a": "rst"}, {"b":"rst"}]' | jq -cr '.[]| { a: ( .a // "-" ) }'
{"a":"rst"}
{"a":"-"}

Transposed

curl https://MyUrl | jq -cr   '.[] | {id: .id, completed: .completed,  content: .content  | sub(","; "") , assignee: ( .assignees[] | objects | .name ) // "-" } '

CodePudding user response:

Using if might be easiest:

assignee: (if .assignees|type == "array" 
           then .assignees[] | objects | .name
           else "-" end)
  • Related