2

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 ?

1
  • 1
    Asking to merge two JSONs makes no more sense than asking to merge a photo and a video. It's entirely possible - once you decide whether you want the picture at the start, at the end, as an overlay in a specific place, inserted every other frame, as a transparent watermark in some corner, in a bigger frame next to the video image... JSON isn't a data structure, it's a serialisation format for many data structures. They won't necessarily mash together - you need to unpick what the datastructures are and how exactly you need them to merge. Commented Aug 3, 2016 at 21:00

1 Answer 1

2

$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
Sign up to request clarification or add additional context in comments.

3 Comments

what if Env had more than one property ? Any to add and merge them together ?
@Scooby you could iterate over $Env.PSObject.Properties and programatically add each member.
could you provide an example for that with made up values ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.