'Display row when field value is absent
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.
Solution 1:[1]
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 ) // "-" } '
Solution 2:[2]
Using if might be easiest:
assignee: (if .assignees|type == "array"
then .assignees[] | objects | .name
else "-" end)
Solution 3:[3]
Thanks to all of you! This minor change seemed to do the trick, with //
'.[] | {id: .id, completed: .completed, content: .content | sub(","; "") , assignee: ( .assignees[] .name // "TBD" )} '
I simplified the .assignees[] | objects | .name portion which made the Alternative // operator work on the first try.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | izissise |
| Solution 2 | peak |
| Solution 3 | Creative Arc |
