Skip to content

Instantly share code, notes, and snippets.

@Badabum
Created August 8, 2017 14:40
Show Gist options
  • Save Badabum/a61e49019fb96bef4d5d9712e07b2af7 to your computer and use it in GitHub Desktop.
Save Badabum/a61e49019fb96bef4d5d9712e07b2af7 to your computer and use it in GitHub Desktop.
Merge two .json objects using PowerShell
function Join-Objects($source, $extend){
if($source.GetType().Name -eq "PSCustomObject" -and $extend.GetType().Name -eq "PSCustomObject"){
foreach($Property in $source | Get-Member -type NoteProperty, Property){
if($extend.$($Property.Name) -eq $null){
continue;
}
$source.$($Property.Name) = Join-Objects $source.$($Property.Name) $extend.$($Property.Name)
}
}else{
$source = $extend;
}
return $source
}
function AddPropertyRecurse($source, $toExtend){
if($source.GetType().Name -eq "PSCustomObject"){
foreach($Property in $source | Get-Member -type NoteProperty, Property){
if($toExtend.$($Property.Name) -eq $null){
$toExtend | Add-Member -MemberType NoteProperty -Value $source.$($Property.Name) -Name $Property.Name `
}
else{
$toExtend.$($Property.Name) = AddPropertyRecurse $source.$($Property.Name) $toExtend.$($Property.Name)
}
}
}
return $toExtend
}
function Json-Merge($source, $extend){
$merged = Join-Objects $source $extend
$extended = AddPropertyRecurse $source $merged
}
#read json files into PSCustomObjects like this:
#$1 = Get-Content 'C:\Beijer\smith-env-settings\1.json' -Raw | ConvertFrom-Json
#$2 = Get-Content 'C:\Beijer\smith-env-settings\2.json'-Raw | ConvertFrom-Json
#Merge properties of the first one and second one.
#$3 = Json-Merge $1 $2
@Badabum
Copy link
Author

Badabum commented Aug 8, 2017

This works in the following way:

  1. For all properties that exist both in the first object and in the second one override override the properties' values of the first object with the values of the second one.
  2. Add properties from which are unique for the second object to the first object
    That's it.

@xom2811
Copy link

xom2811 commented Nov 1, 2017

I believe there is an issue with Json-Merge, I found I had to tweak it like this to get it to work:

function Json-Merge($source, $extend){
$merged = Join-Objects $source $extend
$extended = AddPropertyRecurse $merged $extend
return $extended
}

@DenisIusupov-Parsable
Copy link

There is such functionality already:
$extended = @($source; $extend) | ConvertTo-Json -Depth 100

@webbird
Copy link

webbird commented Mar 8, 2023

Thank you Badabum, this works great for me! The one-liner provided by DenisIusupov-Parsable gives me a different result which is not what I'm after in this case, so visitors should try them both to see which solution works better in their special case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment