Paradigm
Paradigm

Reputation: 371

Merging two JSON objects with the same key into one key

I have two JSON files that I want to combine that may have the same key values in.

file1.json

{
  "parentKey": {
    "secretkey1": "secretkey1value",
    "secretkey2": "secretkey2value"
  }
}

file2.json

{
  "parentKey": {
    "settingKey1": "settingkey1value",
    "settingKey2": "settingkey2value"
  }
}

I want the output of the merged files to combine duplicate keys automatically without having to know which keys are duplicate in the code.

expected-merged.json

{
  "parentKey": {
    "settingKey1": "settingkey1value",
    "settingKey2": "settingkey2value",
    "secretkey1":  "secretkey1value",
    "secretkey2":  "secretkey2value"
  }
}

Is there a way to cleanly achieve this with Powershell?

My attempt was this

$app1 = Get-Content -Path './app1.json' -Raw | ConvertFrom-Json
$app2 = Get-Content -Path './app2.json' -Raw | ConvertFrom-Json

@($app1; $app2) | ConvertTo-Json | Out-File './merged.json'

However it outputs duplicated keys like so

[
    {
        "parentKey":  {
                          "secretkey1":  "secretkey1value",
                          "secretkey2":  "secretkey2value"
                      }
    },
    {
        "parentKey":  {
                          "settingKey1":  "settingkey1value",
                          "settingKey2":  "settingkey2value"
                      }
    }
]

Thanks in advance!

Upvotes: 0

Views: 758

Answers (1)

Theo
Theo

Reputation: 61148

Using your examples, you could do something like this:

$app1 = Get-Content -Path './app1.json' -Raw | ConvertFrom-Json
$app2 = Get-Content -Path './app2.json' -Raw | ConvertFrom-Json

foreach ($item in $app2.parentKey.PsObject.Properties) {
   $app1.parentKey | Add-Member -MemberType NoteProperty -Name $item.Name -Value $item.Value
}

$app1 | ConvertTo-Json | Set-Content -Path './merged.json'

Result:

{
    "parentKey":  {
                      "secretkey1":  "secretkey1value",
                      "secretkey2":  "secretkey2value",
                      "settingKey1":  "settingkey1value",
                      "settingKey2":  "settingkey2value"
                  }
}

Upvotes: 3

Related Questions