Reputation: 51
Input content (somejson.json) is
{ "m1": "1 some m1", "m2": null , "m3" : "unwanted"}
{ "m1": "2 some m1", "m3" : "unwanted"}
{ "m1": "3 some m1", "m2": "3 some m2" , "m3" : "unwanted"}
{ "m1": "4 some m1", "m3" : "unwanted"}
Is there an option to extract, say m1. Also extract m2 if exists ?
Example. For m1 I use the the below command
cat somejson.json |jq '.m1'
Output
"1 some m1"
"2 some m1"
"3 some m1"
"4 some m1"
For m2 I use the the below command
cat somejson.json |jq '.m2'
Output
null
null
"3 some m2"
null
But I want a merged results including both m1 and m2 like below
"1 some m1"
"2 some m1"
"3 some m1"
"3 some m2"
"4 some m1"
Upvotes: 4
Views: 3075
Reputation: 1809
To always extract m1
:
jq '.m1, if (.m2 != null) then .m2 else empty end' somejson.json
Upvotes: 2
Reputation: 198324
Get both values; they will be null
if they don't exist. Then just filter the nulls from the result.
<somejson.json jq '.m1, .m2 | select(. != null)'
Upvotes: 5