简体   繁体   English

如何在jq中检查null或为空,并在jq转换中替换为空字符串

[英]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. 如何在jq中检查null或为空,并在jq转换中替换为空字符串。

Example in below JSON, this is the JQ JSON下面的示例,这是JQ

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: 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[] | code .amazon.items [] | select(.name | contains ("shoes")) code select(.name |包含(“鞋子”)) 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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