jsonjqempty-list

Using if-then-else-end in jq to handle missing values


This is the command I use to pull the info I need:

.results | .[] | {id, name: .general.name, platform: .general.platform, site: .general.site.name, ea_site: .extensionAttributes.[] | select(.definitionId=="57").values.[]}

When .extensionAttributes.[] | select(.definitionId=="57").values.[] is empty, jq does not display any associated items at all.

What I'd like to do is check if .extensionAttributes.[] | select(.definitionId=="57").values.[] < 0 and return empty otherwise return the content. I'm trying to use if-then-else-end, but can't seem to get the syntax correct.

You can find sample data in jqplay here. Line 1218 in the json input has the empty value.

Desired output:

{ "id": "3882", "name": "Kresge-iMac-900", "platform": "Mac", "site": "Arts", "ea_site": "Arts"}
{ "id": "3881", "name": "c-loaner", "platform": "Mac", "site": ".Production", "ea_site": "blank"}

Solution

  • If you fix the test and add parentheses, the code in your comment may do what you intend:

    .results | .[] | {
        id,
        name: .general.name,
        platform: .general.platform,
        site: .general.site.name,
        ea_site: (
            .extensionAttributes.[] | select(.definitionId=="57").values |
            if ( . | length > 0 ) then .[] else "blank" end
        )
    }
    

    Note that if the values array contains multiple elements, you'll get a copy of the object you are creating for each one.