PowerShell how to add something on parsed JSON?

社会主义新天地 提交于 2019-12-03 04:52:49

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 NoteProperty

write-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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!