PowerShell如何在解析的JSON上添加内容?

时间:2014-05-18 08:37:15

标签: json powershell member

我想使用PowerShell在我解析的JSON中添加一些东西。我的代码:

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)
}

我的JSON:

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

我想让BlockC像这样:

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

我试过

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

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

但它不适用于错误:

  

没有添加方法

我尝试了所有可以做的事情(尝试添加方法,使用Add-Member),但都失败了。

补充道:     PS C:\ Users \ Develop7> $ json.BlockA.BlockC |获取会员

   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;}

2 个答案:

答案 0 :(得分:28)

如果您使用的是PowerShell 3.0 / 4.0,则可以使用ConvertFrom-Json cmdlet简化转换。

除此之外,如果您有PS或.Net对象类型,Add-Member cmdlet允许您添加任意属性。以下显示如何基于Json块添加属性:

$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)

答案 1 :(得分:1)

您收到该错误,因为您的$ json实际上是两个对象的集合。其中一个是装配,另一个是字典。管道输出从将程序集加载到Out-Null的行以避免这种情况。例如:

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