PowerShell how to add something on parsed JSON?

I want to add something in my parsed JSON using PowerShell. My code:

function ConvertFromJson([string]$file)
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
    $jsoncontent = Get-Content $file
    $jsonobj = New-Object System.Web.Script.Serialization.JavaScriptSerializer
    $global:json = $jsonobj.DeserializeObject($jsoncontent)
}

My JSON:

{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    },
}

I want make BlockC like this:

{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    },
    "BlockC": {
      "name": "BlockC",
      "value": "Value_C"
    },
}

I tried

$json.BlockA.Add("BlockC", "")

and

$json.BlockA.BlockC.Add("name", "BlockC")

but it doesn't work with the error:

there is no add method

I tried all of i can do (trying Add Method, use Add-Member), but all failed.

added : PS C:UsersDevelop7> $json.BlockA.BlockC | Get-Member

   TypeName: System.String

Name             MemberType            Definition
----             ----------            ----------
Clone            Method                System.Object Clone()
CompareTo        Method                int CompareTo(System.Object value), int CompareTo(string strB)
Contains         Method                bool Contains(string value)
CopyTo           Method                System.Void CopyTo(int sourceIndex, char[] destination, int destinationIndex,...
EndsWith         Method                bool EndsWith(string value), bool EndsWith(string value, System.StringCompari...
Equals           Method                bool Equals(System.Object obj), bool Equals(string value), bool Equals(string...
GetEnumerator    Method                System.CharEnumerator GetEnumerator()
GetHashCode      Method                int GetHashCode()
GetType          Method                type GetType()
GetTypeCode      Method                System.TypeCode GetTypeCode()
IndexOf          Method                int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf...
IndexOfAny       Method                int IndexOfAny(char[] anyOf), int IndexOfAny(char[] anyOf, int startIndex), i...
Insert           Method                string Insert(int startIndex, string value)
IsNormalized     Method                bool IsNormalized(), bool IsNormalized(System.Text.NormalizationForm normaliz...
LastIndexOf      Method                int LastIndexOf(char value), int LastIndexOf(char value, int startIndex), int...
LastIndexOfAny   Method                int LastIndexOfAny(char[] anyOf), int LastIndexOfAny(char[] anyOf, int startI...
Normalize        Method                string Normalize(), string Normalize(System.Text.NormalizationForm normalizat...
PadLeft          Method                string PadLeft(int totalWidth), string PadLeft(int totalWidth, char paddingChar)
PadRight         Method                string PadRight(int totalWidth), string PadRight(int totalWidth, char padding...
Remove           Method                string Remove(int startIndex, int count), string Remove(int startIndex)
Replace          Method                string Replace(char oldChar, char newChar), string Replace(string oldValue, s...
Split            Method                string[] Split(Params char[] separator), string[] Split(char[] separator, int...
StartsWith       Method                bool StartsWith(string value), bool StartsWith(string value, System.StringCom...
Substring        Method                string Substring(int startIndex), string Substring(int startIndex, int length)
ToCharArray      Method                char[] ToCharArray(), char[] ToCharArray(int startIndex, int length)
ToLower          Method                string ToLower(), string ToLower(System.Globalization.CultureInfo culture)
ToLowerInvariant Method                string ToLowerInvariant()
ToString         Method                string ToString(), string ToString(System.IFormatProvider provider)
ToUpper          Method                string ToUpper(), string ToUpper(System.Globalization.CultureInfo culture)
ToUpperInvariant Method                string ToUpperInvariant()
Trim             Method                string Trim(Params char[] trimChars), string Trim()
TrimEnd          Method                string TrimEnd(Params char[] trimChars)
TrimStart        Method                string TrimStart(Params char[] trimChars)
Chars            ParameterizedProperty char Chars(int index) {get;}
Length           Property              System.Int32 Length {get;}
Asked By: Blank
||

Answer #1:

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)
Answered By: RickH

Answer #2:

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
Answered By: Alexander Obersht
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles