PowerShell how to add something on parsed JSON?
If you're using PowerShell 3.0/4.0 you can simplify your conversion using the ConvertFrom-Json cmdlet.
Beyond that, if you have PS or .Net Object Types, the Add-Member cmdlet allows you to add arbitrary properties. The following shows how to add a property based on a Json block:
$json = @"{ "BlockA": { "BlockB": { "name": "BlockB", "value": "Value_B" } }}"@$blockcvalue =@" { "name":"BlockC", "value":"ValueC" }"@$jobj = ConvertFrom-Json -InputObject $json$jobj.BlockA | add-member -Name "BlockC" -value (Convertfrom-Json $blockcvalue) -MemberType NotePropertywrite-host (ConvertTo-Json $jobj)
You get that error because your $json is actually a collection of two objects. One of them is an assembly and the other one is a dictionary. Pipe output from the line that loads assembly to Out-Null
to avoid that. Example:
function ConvertFrom-Json([String]$sRawJson) { [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") ` | Out-Null $oJsSerializer = ` New-Object System.Web.Script.Serialization.JavaScriptSerializer return $oJsSerializer.DeserializeObject($sRawJson)}$sBaseContent = @"{ "BlockA": { "BlockB": { "name": "BlockB", "value": "Value_B" } }}"@$sBlockcContent = @"{ "name": "BlockC", "value": "Value_C"}"@$jsonBaseObj = ConvertFrom-Json($sBaseContent)$jsonBlockcObj = ConvertFrom-Json($sBlockcContent)$jsonBaseObj.BlockA.Add("BlockC", $jsonBlockcObj)$jsonBaseObj