简体   繁体   中英

How to check for null or empty in jq and substitute for empty string in jq transformation

How to check for null or empty in jq and substitute for empty string in jq transformation.

Example in below JSON, this is the JQ

JQ:

   .amazon.items[] | select(.name | contains ("shoes")) as $item |
   {
        activeItem: .amazon.activeitem,
        item : {
         id : $item.id,
         state : $item.state,
         status : if [[ $item.status = "" or $item.status = null ]]; 
        then 'IN PROCESS' ; else $item.status end
         }  
   }

JSON:

  {
    "amazon": {
      "activeitem": 2,
      "items": [
        {
          "id": 1,
          "name": "harry potter",
          "state": "sold"
        },
        {
          "id": 2,
          "name": "adidas shoes",
          "state": "in inventory"
        },
        {
          "id": 3,
          "name": "watch",
          "state": "returned"
        },{
          "id": 4,
          "name": "Nike shoes",
          "state": "in inventory"
        }
      ]
    }
  } 

I want to add a default string "In Process" if the status is empty or Null.

Based on Item condition, using the query below and take the first object from the filtered results.

code .amazon.items[] | select(.name | contains ("shoes")) code

Expected Output:

{
    "activeitem": 2,
    "item": {
      "id": 2,
      "name": "adidas shoes",
      "state": "in inventory",
      "status": "IN PROCESS"
    }
  }

The key here is to use |= :

.amazon.item.status |=
  if . == null or . == ""
  then "IN PROCESS"
  else .
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM