Home > Back-end >  Updating JSON Array of Objects with NULL Value in Powershell When Key is Present
Updating JSON Array of Objects with NULL Value in Powershell When Key is Present

Time:02-16

I am new to Powershell and am having trouble doing something that I imagine may be pretty simple, but not having luck so far.

I have an array with two objects in it. It looks like this basically:

[

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

]

My goal is to update the score value in the second object. I have had luck doing so when the key's value is already present as a String, but am not understanding why I am unable to get this to work when the key is present but the value is null (as shown above).

I have tried using a function which I learned about when doing a search for a previously posted question trying to do something similar:

Set Value of Nested Object Property by Name in PowerShell

The function from that question looks like this:

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

and can be called like this:

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

I am not sure why it matters if the value is NULL or not. It can find the key, but just not doing anything if its value is NULL.

My apologies if this already out there. Powershell is just a little different than anything I have worked with before! Any help is greatly appreciated! :)

CodePudding user response:

The object generated by your JSON string is an array of two objects:

$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

Updating the Value of the score property considering the JSON will always be the same, meaning, the element 1 of the array will always have that property would be as simple as:

$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"
  }
]

On the other hand, if the arrangement of the objects wouldn't be always the same, you could loop over all elements of the array searching for that property and, once found, update it. For example:

# 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
  • Related