簡體   English   中英

jq將一個文件的內容更新為另一個作為鍵值

[英]jq update contents of one file to another as key value

我正在嘗試從branch2.json.Employes值更新branch.json.branch2值使用jq,如何將一個文件的內容合並到另一個文件中?

我已經嘗試過了,但是它確實起作用了,它只是打印原始數據而不更新細節

#!/bin/sh
#call file with branch name for example ./update.sh branch2
set -xe
branchName=$1
fullPath=`pwd`/$1".json"
list=$(cat ${fullPath})
branchDetails=$(echo ${list} | /usr/local/bin/jq -r '.Employes')
newJson=$(cat branches.json | 
      jq --arg updateKey "$1" --arg updateValue "$branchDetails" 'to_entries | 
       map(if .key == "$updateKey"
          then . + {"value":"$updateValue"} 
          else . 
          end) | 
          from_entries')

回聲$ newJson&> results.json

branch1.json

{
  "Employes": [
    {
      "Name": "Ikon",
      "age": "30"
    },
    {
      "Name": "Lenon",
      "age": "35"
    }
  ]
}

branch2.json

{
  "Employes": [
    {
      "Name": "Ken",
      "age": "40"
    },
    {
      "Name": "Frank",
      "age": "23"
    }
  ]
}

來自at的brances.json / results.json

{
  "branch1": [
      {
        "Name": "Ikon",
        "age": "30"
      },
      {
        "Name": "Lenon",
        "age": "35"
      }
    ],
  "branch2": [
      {
        "Name": "Ken",
        "age": "40"
      },
      {
        "Name": "Frank",
        "age": "23"
      }
    ]

}

注意:在任何給定點,我都沒有所有分支文件的列表,因此腳本僅負責更新該分支的詳細信息。

如果文件名是您要更新的屬性的名稱,則可以利用input_filename選擇文件。 無需測試,只需傳入您要更新的文件即可。 請注意輸入文件中傳遞的順序。

根據需要合並文件的內容。 要簡單地替換,只需執行簡單的任務即可。

$ jq 'reduce inputs as $i (.;
    .[input_filename|rtrimstr(".json")] = $i.Employes
)' branches.json branch{1,2}.json

您的腳本只需要是:

#!/bin/sh
#call file with branch name for example ./update.sh branch2
set -xe
branchName=$1
newJson=$(jq 'reduce inputs as $i (.; .[input_filename|rtrimstr(".json")] = $i.Employees)' branches.json "$branchName.json")

暫無
暫無

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

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