Using PowerShell to Handle JSON Strings

Suppose I have a JSON part in a PowerShell string, for example

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

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

Therefore, trying to understand, 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 return from ConvertFrom-Jsonhas a type PSCustomObjectthat does not allow adding properties. So the 3rd line explodes:

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 best suited for this without bringing too much complexity?

+4
source share
1 answer

do , . Add-Member.

$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

, PowerShell Add-Member :

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

, , , v4, , v3.

+6

All Articles