I'm trying to edit an object in PowerShell that was created through importing a JSON file. I'm then trying to use dot notation to access or amend properties of the object.
For example, below is a JSON sample and a code snippet
{
"menus": {
"menu1": {
"position": "left"
}
}
}
# Import the file
$settings = Get-Content -Path somefile.json | ConvertFrom-Json
# Specify the property to change
$valueToChange = "menus.menu1.position"
$value = "left"
# Set the appropriate value according to the variables above
$settings.$valueToChange = $value
The above gives me:
Exception setting "menus.menu1.position": "The property 'menus.menu1.position' cannot be found on this object. Verify that the property exists and can be set."."
Whereas, if I do the exact same without the variables in the dot notation, it works.
# Import the file
$settings = Get-Content -Path somefile.json | ConvertFrom-Json
# Specify the property to change
$value = "left"
# Set the appropriate value according to the variables above but with a hard coded dot notation
$settings.menus.menu1.position = $value
I'm going to guess that it's related to the variable being a string or similar but the issue is that I need to programmatically calculate the dot notation for setting the values in the file, or at least allow a user to specify it.
I've actually worked around the issue now (by just avoiding this approach entirely) but I wanted to see if this was possible.
Even a clean alternative to dot notation would be good to see. The only reason I went with it in the first place is because my real JSON object is quite complicated and the dot notation is very straightforward and easy to follow.