Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Ternary logic" for returned value: foo, bar or error

I've got two different JSON structures to retrieve a specific object value from, basically something like this

{
    "one": {
        "foo": {
            "bar": "baz"
        }
    }
}

and another like that

{
    "two": {
        "foo": {
            "bar": "qux"
        }
    }
}

I'd like to return the bar value in both cases plus an additional return variant error in case neither case 1 - baz - nor case 2 - qux - matches anything (i.e. matches null).

Is there a simple way to do that with just jq 1.6?

Update: Here are snippets of actual JSON files:

/* manifest.json, variant A */
{
    "browser_specific_settings": {
        "gecko": {
            "id": "{95ad7b39-5d3e-1029-7285-9455bcf665c0}",
            "strict_min_version": "68.0"
        }
    }
}

/* manifest.json, variant B */
{
    "applications": {
        "gecko": {
            "id": "j30D-3YFPUvj9u9izFoPSjlNYZfF22xS@foobar",
            "strict_min_version": "53.0"
        }
    }
}

I need the id values (*gecko.id so to speak) or error if there is none:

{95ad7b39-5d3e-1029-7285-9455bcf665c0}
j30D-3YFPUvj9u9izFoPSjlNYZfF22xS@foobar
error
like image 240
dabbl0r Avatar asked Dec 14 '22 10:12

dabbl0r


2 Answers

You can use a filter as below that could work with both your sample JSON content provided

jq '.. | if type == "object" and has("id") then .id else empty end'

See them live jqplay - VariantA and jqplay - VariantB

Note: This only gets the value of .id when it is present, see others answers (oguz ismail's) for displaying error when the object does not contain the required field.

like image 97
Inian Avatar answered Dec 27 '22 00:12

Inian


(.. | objects | select(has("id"))).id // "error"

This will work with multiple files and files containing multiple separate entities.

jqplay demo

like image 25
oguz ismail Avatar answered Dec 27 '22 00:12

oguz ismail