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

时间:2019-01-23 17:21:35

标签: json select jq

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

JSON下面的示例,这是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"
        }
      ]
    }
  } 

如果状态为空或为空,我想添加一个默认字符串“处理中”。

根据项目条件,使用以下查询,并从过滤的结果中获取第一个对象。

code        .amazon.items [] | select(.name |包含(“鞋子”)) code

预期输出:

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

1 个答案:

答案 0 :(得分:0)

此处的关键是使用|=

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