使用JQ使用来自另一个JSON的值更新一个JSON文件值 [英] Update one JSON file values with values from another JSON using JQ

查看:171
本文介绍了使用JQ使用来自另一个JSON的值更新一个JSON文件值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个JSON文件:

So I have two JSON files:

bosh.json:

{
  "key_pair_name": "my-aws-keypair",
  "ssh_private_key": "my-key-name",
  "trusted_certificates": "my-trusted-certs"
}

model.json:

{
  "trusted_certificates": "vault-supplied-value",
  "vm_password_type": "generate"
}

我想用bosh.json文件更新model.json文件,所以它看起来像这样:

and I want to update the model.json file with the bosh.json file so it looks like this:

{
  "trusted_certificates": "my-trusted-certs",
  "vm_password_type": "generate"
}

我尝试过:

jq --argfile bosh bosh.json '. += $bosh' model.json

但是我得到的钥匙太多

{
  "trusted_certificates": "my-trusted-certs",
  "vm_password_type": "generate",
  "key_pair_name": "my-aws-keypair",
  "ssh_private_key": "my-key-name"
}

jq --argfile bosh bosh.json '. + $bosh' model.json

也一样...

{
  "trusted_certificates": "my-trusted-certs",
  "vm_password_type": "generate",
  "key_pair_name": "my-aws-keypair",
  "ssh_private_key": "my-key-name"
}

与此同时

jq --argfile bosh bosh.json '. = $bosh' model.json

产生不正确的键...

yields the incorrect keys...

{
  "key_pair_name": "my-aws-keypair",
  "ssh_private_key": "my-key-name",
  "trusted_certificates": "my-trusted-certs"
}

有人知道如何使用jq获得预期结果吗? 顺便说一句,我不能使用密钥的值进行更新,因为在其他排列中我会得到意想不到的结果...

Does anyone have any ideas how to get the expected results using jq? by the way, I cannot use the value of the key for the updates, as i will have unexpected results in other permutations...

推荐答案

要求不是很清楚,但这是一种解释的解决方案.可以轻松修改此解决方案,以与其他明显的解释相匹配.

The requirements are not completely clear, but here's the solution to one interpretation. This solution can easily be modified to match the other obvious interpretation.

假设文件bosh.jq包含以下jq程序:

Assuming the file bosh.jq contains the following jq program:

reduce keys[] as $k (.; if $bosh|has($k) then .[$k] = $bosh[$k] else . end)

然后输入命令:

jq --argfile bosh bosh.json -f bosh.jq model.json

实际上将发出model.json的编辑版本.

will in effect emit the edited version of model.json.

如果您希望采用无减少量的方法,请考虑:

If you prefer a reduce-free approach, consider:

with_entries(.key as $k | if $bosh|has($k) then .value = $bosh[$k] else . end )

请注意,if $bosh|has($k) ...if $bosh[$k] ...不同.

这篇关于使用JQ使用来自另一个JSON的值更新一个JSON文件值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆