【问题标题】:Updating JSON Array of Objects with NULL Value in Powershell When Key is Present存在键时在 Powershell 中更新具有 NULL 值的对象的 JSON 数组
【发布时间】:2022-02-16 10:17:52
【问题描述】:

我是 Powershell 的新手,在做一些我认为可能很简单的事情时遇到了麻烦,但到目前为止还没有运气。

我有一个包含两个对象的数组。基本上是这样的:

[

{
"name":"John",
"age":30,
...
...
},
{
"score":null,
"vehicle":"Camaro",
"engine":"V8",
...
...
}

]

我的目标是更新第二个对象中的 score 值。当键的值已经作为字符串存在时,我很幸运这样做,但我不明白为什么当键存在但值为 null 时我无法使其工作(如上所示)。

我尝试使用我在搜索以前发布的问题时了解到的一个功能,尝试做类似的事情:

Set Value of Nested Object Property by Name in PowerShell

该问题的函数如下所示:

function SetValue($object, $key, $Value)
{
    $p1,$p2 = $key.Split(".")
    if($p2) { SetValue -object $object.$p1 -key $p2 -Value $Value }
    else { $object.$p1 = $Value }
}

并且可以这样调用:

SetValue -object $Obj -key $Key -Value $Value

我不确定该值是否为 NULL 为什么很重要。它可以找到密钥,但如果它的值为 NULL,则什么也不做。

如果这已经存在,我深表歉意。 Powershell 与我以前使用过的任何东西都有一点不同!任何帮助是极大的赞赏! :)

【问题讨论】:

    标签: json powershell null key-value


    【解决方案1】:

    您的 JSON 字符串生成的对象是一个包含两个对象的数组:

    $json = @'
    [
      {
        "name":"John",
        "age":30,
      },
      {
        "score":null,
        "vehicle":"Camaro",
        "engine":"V8"
      },
    ]
    '@ | ConvertFrom-Json
    
    $json[0] # => Element 0 of the Array
    
    name age
    ---- ---
    John  30
    
    $json[1] # => Element 1 of the Array
    
    score vehicle engine
    ----- ------- ------
          Camaro  V8
    

    更新score属性的考虑到JSON总是相同的,意思是数组的元素1将始终具有该属性,如下所示:

    $json[1].score = 'hello' # => Updating the property value
    
    $json | ConvertTo-Json   # => Converting the array back to Json
    
    [
      {
        "name": "John",
        "age": 30
      },
      {
        "score": "hello",
        "vehicle": "Camaro",
        "engine": "V8"
      }
    ]
    

    另一方面,如果对象的排列并不总是相同,您可以遍历数组的所有元素来搜索该属性,并在找到后对其进行更新。例如:

    # For each element of the array
    foreach($object in $json) {
        # if this object has a property with name `score`
        # assign that `NoteProperty` to the variable `$prop`
        if($prop = $object.PSObject.Properties.Item('score')) {
            # update the Value of the `NoteProperty`
            $prop.Value = 'hello'
        }
    }
    $json | ConvertTo-Json # Convert it back
    

    【讨论】:

    • 不错。非常感谢!我想它会保持不变,并且应该注意到我也尝试过并且成功地定位了一个特定元素,就像你在你的答案中那样,这对我有用,但我不确定这些元素是否会是以相同的顺序。让我感到困惑的是,我可以在设置值时更新,但不能在它为 NULL 时进行更新。明天我会试一试,然后告诉你。非常感谢! :)
    • @finiteloop 很乐意提供帮助,如果第二个对象始终是具有属性 score 的对象,那么在第一个示例之后应该没有任何问题。如果您不确定,我建议您使用循环(最后一个示例)
    • 伙计,我比我计划的要早一点试了一下,因为今天这让我发疯了,所以我急于测试这个。循环遍历数组中的对象元素效果很好,我不再遇到我遇到的奇怪的 NULL 值设置问题。我不知道 PSObject!我会阅读更多!使用 JSON 元素这样的循环对我来说非常熟悉,因为我使用了我知道的其他语言,所以这真的很有帮助。将此标记为正确!再次感谢!
    • @finiteloop 很高兴听到这个消息!你可以从herethis complements it 开始你的PSObject 研究:)
    猜你喜欢
    • 2020-04-28
    • 2018-04-05
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2021-10-06
    • 2020-04-14
    相关资源
    最近更新 更多