5

providing I have the following JSON

{
    "firstName":  "Frank",
    "lastName":  "Smith",
    "age":  "25",
    "address":  {
                    "streetAddress":  "21 3rd st",
                    "city":  "New York",
                    "state":  "NY",
                    "postalCode":  "10021"
                },
    "phoneNumber":  [
                        {
                            "type":  "home",
                            "number":  "212 555-1234"
                        },
                        {
                            "type":  "fax",
                            "number":  "646 555-4567"
                        }
                    ]
}

I need to be able to update a value using dotted notation.

$path = "C:\somePath\test.json"
$node = "address.streetAddress"         # should also work with "phoneNumber[0].number"
$value = "21 Jump St."

$config = Get-Content -Path $path -Raw | ConvertFrom-Json
$config.$node = $value
Write-Host $config.$node

#Set-Content $path $($config | ConvertTo-Json)

The problem I'm getting is that the property cannot be found.

Exception setting "address.streetAddress": "The property 'address.streetAddress' cannot be found on this object. Verify that the property exists and can be set."

What do I need to do to be able to pass in dotted notation, and update the appropriate value?

2 Answers 2

4

While you can put a single property name in a variable and use that to access the property, you can't do that for multiple, dotted properties. You can work around this by using Invoke-Expression:

Invoke-Expression "`$config.$node = `$value"
Sign up to request clarification or add additional context in comments.

1 Comment

That's great, thanks. I didn't realize that's how it all came together.
2

Shortest way around it is:

$config.$($node) = $value

Level of nesting does not matter, You can do this:

$config.$($node).$($subnode).$($subSubNode) = $value   

You can also refer to properties in objects like this:

$config.$($node.nodename)=$value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.