如何在jq中检查null或为空,并在jq转换中替换为空字符串 [英] How to check for null or empty in jq and substitute for empty string in jq transformation

查看:548
本文介绍了如何在jq中检查null或为空,并在jq转换中替换为空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

JSON下面的示例,这是JQ

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(鞋子")) code

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

预期输出:

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

推荐答案

此处的关键是使用|=:

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

这篇关于如何在jq中检查null或为空,并在jq转换中替换为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆