I have a json file: example.json
{
"list": [
{
"entryA": {
"item1": "foo",
"item2": "bar"
}
},
{
"entryB": {
"item1": "oof",
"item2": "rab"
}
}
]
}
I would like the output to be the contents of entryB:
{
"item1": "oof",
"item2": "rab"
}
however, using the example from the manual for Optional Object Identifier-Index: .foo?, I get these results:
$ jq '.list[] | .entryB?' example.json
null
{
"item1": "oof",
"item2": "rab"
}
$ jq '.list[] | .["entryB"]?' example.json
null
{
"item1": "oof",
"item2": "rab"
}
How can I format the JQ Query to not include a null output for entryA?
CodePudding user response:
By using the alternative operator // you can defect to empty if the first alternative does not exist.
jq '.list[] | .entryB // empty' example.json
{
"item1": "oof",
"item2": "rab"
}
CodePudding user response:
One option would be using to_entries such as
jq '.list[] | to_entries[] | select(.key=="entryB") | .value' example.json
