簡體   English   中英

如果條件滿足,JQ 將 key 添加到 json

[英]JQ add key to json if condition satisfies

有很多解決方案,但遺憾的是沒有一個對我有用,所以這是我的問題示例

{
  "name": "bar some random string",
  "thing": true,
  "new_key": 0
}
{
  "name": "biz again another length words",
  "thing": true,
  "new_key": 0
}

所以,我的問題是如果名稱包含“隨機”添加鍵值“包含”:1否則“包含”:0

我試過的解決方案是

if .name == "random" then . |= . + {"Contains": 1} else . |= . + {"Contains": 0} end 

我需要的是

{
  "name": "bar some random string",
  "thing": true,
  "new_key": 0
  "Contains": 1
}
{
  "name": "biz again another length words",
  "thing": true,
  "new_key": 0
  "Contains": 0
}

保持簡短和甜蜜:

.Contains = (if .name | contains("random")
             then 1 else 0 end)

找到答案

if .name  | contains("random") then . |= . + {"Contains": 1} else . |= . + {"Contains": 0} end 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM