Home > Back-end >  Powershell: Trying to set value in json
Powershell: Trying to set value in json

Time:11-30

I have a a json file in which I am trying to set the value of one of the nodes:

primaryContact : {
      loginName : null
}

Without going into detail, I have the path to this value stored in the value $name. e.g.:

$name = primaryContact.loginName

How can I change this value while referencing $name as part of the statement? I have converted json properly.

This works:

jsonFile.primaryContact.loginName = "some value"

I need to do something like this:

jsonFile.$name = "some value"

If I try this last statement I get this error:

"The property 'primaryContact.loginName' cannot be found on this object. Verify that the property exists and can be set."

CodePudding user response:

$jsonFile.$name is not going to work, because PowerShell will attempt to resolve a single property named primaryContact.loginName instead of first primaryContact and then loginName.

You need to dereference each member level individually - first get the value of primaryContact from the root object, then assign to the loginName property on the resulting object:

function Set-ByPath
{
  param(
    $RootObject,
    [string]$Path,
    $NewValue
  )

  # split path into individual member names
  $pathParts = $Path.Split('.')

  # we'll use this variable to keep track of the last member we resolved
  $object = $RootObject

  for($i = 0; $i -lt $pathParts.Length; $i  ){
    $memberName = $pathParts[$i]
    if($i -eq $pathParts.Length - 1){
      # last part of the member chain, assign value and return
      $object.$memberName = $newValue
      return
    }

    # we haven't yet reach the last member, continue to get the next property in the chain
    $object = $object.$memberName
  }
}

Now you can do:

$name = 'primaryContact.loginName'
$data = '{"primaryContact" : { "loginName" : null }}' |ConvertFrom-Json

Set-ByPath -RootObject $data -Path $name -NewValue "new login name goes here"
  • Related