4

Suppose I have a piece of JSON in a PowerShell string, e.g.

$s = '{"foo":"hello"}'

My goal is to turn this into an object that I can manipulate (e.g. changing/adding properties), and then convert back to a json string.

So trying the obvious, I write:

$o = $s | ConvertFrom-Json    # convert the json string to an object
$o.foo = "hello2"             # change an existing prop
$o.bar = "World"              # add a new prop
$s2 = $o | ConvertTo-Json     # convert back into a json string

The problem is that the object I get back from ConvertFrom-Json is of type PSCustomObject, which doesn't allow adding properties. So the 3rd line blows up with:

Exception setting "bar": "The property 'bar' cannot be found on this object. Verify that the property exists and can be set." At line:1 char:1

Question: what is the best way to approach this without bringing too much complexity?

1 Answer 1

9

Custom objects do allow you to add properties, you just have to do it correctly. You need the Add-Member cmdlet.

$o = $s | ConvertFrom-Json    # convert the json string to an object
$o.foo = "hello2"             # change an existing prop
Add-Member -InputObject $o -MemberType NoteProperty -Name 'bar' -Value "World"              # add a new prop
$s2 = $o | ConvertTo-Json     # convert back into a json string

It is worth noting that depending on your version of PowerShell that Add-Member line could be simplified to:

$o | Add-Member 'bar' 'World'

I'm not sure what version that syntax became acceptable, but I know it works in v4 and I think it works in v3.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, the simpler $o | Add-Member 'bar' 'World' does work. Not as simple as a simple assignment, but good enough. Thanks!

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.