如果不是数组Powershell,请将JSON属性更改为数组

问题描述

我有一个JSON,我想检查它是否为数组,如果不是,我想更新JSON并将其更改为数组

RedirectToIdentityProvider = async n =>
{
    if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
    {
        var nonceKey = HttpContext.Current.Response.Cookies.AllKeys.Where(x => x.Contains("nonce")).FirstOrDefault();
        if (nonceKey != null)
        {
            var nonce = HttpContext.Current.Response.Cookies.Get(nonceKey);
            nonce.SameSite = SameSiteMode.None
        }
    }

到目前为止的代码

{
    "Customer": [{
        "id": "123"
    }],"address": {
    "type": "home","name": "what","description": "","adi:water": {
      "type": "comp","location": "grass"
    },"att": [
      {
        "name": "cat","type": "int"
      },{
        "name": "ds","type": "string"
      }
    ]
  }
}

#For example address is not an array,I want to change so address is an array of one single object

我希望地址为数组。我可以在Powershell中这样做吗?

解决方法

使用ForEach-Object并通过将address属性值括在array-subexpression operator中的@(...)中,以确保它是一个数组(如果已经是数组,没有任何变化 [1] ):

@'
{
  "Customer": [
      {
          "id": "123"
      }
  ],"address": {
      "type": "home","name": "what","description": "","adi:water": {
          "type": "comp","location": "grass"
      },"att": [
          {
              "name": "cat","type": "int"
          },{
              "name": "ds","type": "string"
          }
      ]
  }
}
'@ | ConvertFrom-Json | 
  ForEach-Object { 
    $_.address = @($_.address | Select-Object * -ExcludeProperty streets)
    $_ 
  } |
    ConvertTo-Json -Depth 4

请注意分配后的独立$_语句:使用PowerShell的 output (到下一个管道段)。 em>隐式输出功能-参见this answer

注意:默认情况下, ConvertTo-Json 将序列化深度限制为2,因此上面使用了-Depth 4来防止数据丢失。通常,请记住您可能必须将-Depth参数传递给ConvertTo-Json以防止数据丢失-请参见this post [2]

上面的代码产生了以下内容,表明address属性现在是一个数组:

{
  "Customer": [
    {
      "id": "123"
    }
  ],"address": [
    {
      "type": "home","adi:water": {
        "type": "comp","att": [
        {
          "name": "cat","type": "int"
        },{
          "name": "ds","type": "string"
        }
      ]
    }
  ]
}

[1]从技术上讲,会创建一个现有数组的(浅)副本,但这在这里没有任何区别。
要了解有关@()运算符的更多信息,请参见this answer

[2]此要求麻烦且容易遗漏,但出于向后兼容的目的并未更改。但是,当(可能是默认值)-Depth值不足时, PowerShell 7.1版至少会发出警告 :请参阅this PR和相关讨论在GitHub issue #8393中。
另外,在将JSON cmdlet的实现从Newtonsoft.Json库移到内置的System.Text.Json API中的某个时刻,可能会在v7.1之后的某个时刻重新讨论该问题,这将在不可避免地需要进行重大更改-请参见this PR