![](/img/trans.png)
[英]Jq - add a key/value to one JSON file if such key/value exists in another JSON file
[英]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.