skip to Main Content

I want to merge two JSON objects that has a common key

Object A

{
  "extensions": { 
    "app_name": "extensions-prod"
  },
  "plugins": { 
    "app_name": "plugins-prod" 
  }
}

Object B

{
  "plugins": { 
    "project_name": "plugins-prod" 
  }
}

Desired output:

{
  "plugins": { 
    "project_name": "plugins-prod",
    "app_name": "plugins-prod" 
  }
}

I did look into other SO posts but were not very useful as the structure I have is different. Also the json objects are bash variables and not contained in a file.

[Edit] I would not know what the common key would be since the JSON objects are being generated dynamically in a CI environment.

2

Answers


  1. One possible solution that is admittedly pedestrian but which avoids the generality and potential complexity of a "deep merge" would be:

    jq '.plugins += input.plugins' A.json B.json
    

    If you want the ordering of keys shown in the Q, you could modify this to:

     jq '.plugins = input.plugins + .plugins' A.json B.json
    

    There are many variations of the above theme.

    Login or Signup to reply.
  2. This should achieve what’s expected :

    #!/usr/bin/env bash
    
    A='{
      "extensions": { 
        "app_name": "extensions-prod"
      },
      "plugins": { 
        "app_name": "plugins-prod" 
      }
    }'
    B='
    {
      "plugins": { 
        "project_name": "plugins-prod" 
      }
    }'
    
    jq -s 'map(to_entries) |
           add |
           group_by(.key) |
           map(select(length == 2) |
               { key: first | .key,
                 value: map(.value) | add
               }
              ) |
           from_entries' <<< "$A $B"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search