Update one JSON file values with values from anoth

2019-03-03 05:16发布

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"
}

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"
}

I tried this:

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

but I get too many keys

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

and

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

yeilds the same...

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

while this

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"
}

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...

2条回答
聊天终结者
2楼-- · 2019-03-03 05:34

jq solution:

jq --argfile bosh bosh.json 'with_entries( 
         if $bosh[.key] then .value = $bosh[.key] else . end)' model.json

The output:

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

  • if $bosh[.key] then .value = $bosh[.key] else . end - update model's value only for matched keys
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-03 05:49

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.

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

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

then the command:

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

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

Using with_entries

If you prefer a reduce-free approach, consider:

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

Note that if $bosh|has($k) ... is NOT the same as if $bosh[$k] ....

查看更多
登录 后发表回答