簡體   English   中英

使用 JQ 搜索多個鍵:值對並已替換為定義變量

[英]With JQ search multiple key: value pairs and replace with define variable already

我有幾個 json 文件和下面的兩個或一個鍵,可能存在或不存在。

{
  "parent1": {
    "parent1key": "parent1value"
  },
  "parent2": {
    "parent2key": "parent2value"
  }

}

如果兩個 key: 對總是存在,我可以使用

jq --arg parent1keyarg $MyVAL1 --arg parent2keyarg $MyVAL2 '(..|objects|select(.parent1key ).parent1key ) |= $parent1keyarg | (..|objects|select(.parent2key).parent2key) |= $parent2keyarg ' jsonfile.json

  1. 我想找到parent1keyparent2key ,如果找到一個或兩個,然后用運行時生成的變量替換它們。 如果沒有找到 key: 值,則忽略它而不是遇到錯誤。

  2. 我想使用jq --arg而不是 bash if條件,只是為了確保 JSON 格式准確(或者 jq 對我來說很有趣)。

我們如何在 JQ 中編寫條件是我無法從 jq 手冊中弄清楚的。

如果有人可以幫助我,我將不勝感激。

謝謝!

根據您的描述,以下內容似乎就足夠了:

if has("parent1key") then .parent1key = $a
else . end 
| if has("parent2key") then .parent2key = $b
  else . end

如果你需要更多,那么我會使用上面的walk

walk(if type=="object"
     then if has("parent1key") then .parent1key = $a
          else . end 
          | if has("parent2key") then .parent2key = $b
            else . end
     else . end)

一個簡單的walk/1表達式就足以遞歸地檢查密鑰是否存在。 它可以通過使其成為一個功能來進一步改進。

def replace(k; v):
   walk(if type == "object" and has(k) then .[k] = v else . end);

replace("parent1key"; "foo") | replace("parent2key"; "bar")

replace 的第一個參數采用要replace其值的鍵名。 只需通過管道傳輸任意數量的鍵和您想要更改的關聯值。

( .parent1.parent1key | select( . ) ) |= $parent1keyarg |
( .parent2.parent2key | select( . ) ) |= $parent2keyarg

暫無
暫無

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

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