skip to Main Content

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"}

3

Answers


  1. 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.

    Login or Signup to reply.
  2. You can use the more concise // operator:

    jq '.results[] | {
        id, name: .general.name, platform: .general.platform, site: .general.site.name,
        ea_site: ((.extensionAttributes.[] | select(.definitionId=="57").values.[]) // null)
      }' data.json
    
    # 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": null
    }
    
    Login or Signup to reply.
  3. A simple way to use if...then...else...end here based on your own attempt is as follows:

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

    Please note that in jq terminology, the "empty list" is quite different from empty: the latter is both a keyword and a reference to the empty stream. (For me, it was your reference to line 1218, in which the value is [], that clarified the intent of the question.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search