Update one JSON file values with values from another JSON using JQ

后端 未结 2 400
梦毁少年i
梦毁少年i 2021-01-23 18:45

So I have two JSON files:

bosh.json:

{
  \"key_pair_name\": \"my-aws-keypair\",
  \"ssh_private_key\": \"my-key-name\",
  \"trusted_certific         


        
相关标签:
2条回答
  • 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] ....

    0 讨论(0)
  • 2021-01-23 19:39

    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
    0 讨论(0)
提交回复
热议问题