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

匆匆过客 提交于 2021-02-19 07:47:06

问题


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

回答1:


The key here is to use |=:

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


来源:https://stackoverflow.com/questions/54332521/how-to-check-for-null-or-empty-in-jq-and-substitute-for-empty-string-in-jq-trans

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!