Search code examples
jsonbatch-processingjq

"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

Solution

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

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

    jqplay demo