简体   繁体   中英

Using PowerShell to process a JSON string

Suppose I have a piece of JSON in a PowerShell string, eg

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

My goal is to turn this into an object that I can manipulate (eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM