Search code examples
jsonwindowspowershellpowershell-2.0powershell-3.0

merging two Jsons in powershell


I have the following two Objects , which have been got from 2 Json file using:

$Env = ConvertFrom-Json "$(get-content "C:\chef\environments.json")"
$Roles = ConvertFrom-Json "$(get-content "C:\chef\roles.json")"

Heres the out put after conversion :

PS C:\chef> $Env

run_list
--------
{recipe[djin_chef-max_any::default]}


PS C:\chef> $Roles


7-zip             : @{home=%SYSTEMDRIVE%\7-zip}
cookbook_versions :
default           : @{env=development}
modmon            : @{env=dev}
paypal            : @{artifact=%5BINTEGRATION%5D}
seven_zip         : @{url=https://djcm-zip-local/djcm/chef}
task_sched        : @{credentials=XN$q}
windows           : @{password=K1N5}

I need to merge these two Json objects in powershell and I tried the following:

PS C:\chef> $Roles+$Env
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At line:1 char:1
+ $Roles+$Env
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Is there another elegant way of doing it if I am doing it wrong or why am I getting this error ?


Solution

  • $Env only has one property, so you could add a new member to $Roles:

    $Roles | Add-Member -NotepropertyName run_list -NotePropertyValue $Env.run_list
    

    This syntax work in PowerShell v3, but you listed v2 and v2 in your tags.. so for v2:

    $Roles | Add-Member -MemberType NoteProperty -Name run_list -Value $Env.run_list