Created
August 8, 2017 14:40
-
-
Save Badabum/a61e49019fb96bef4d5d9712e07b2af7 to your computer and use it in GitHub Desktop.
Merge two .json objects using PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
}
There is such functionality already:
$extended = @($source; $extend) | ConvertTo-Json -Depth 100
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
This works in the following way:
That's it.