Using PowerShell to process a JSON string

时间:2022-04-26 00:35:36

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

假设我在PowerShell字符串中有一段JSON,例如

$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.

我的目标是将其转换为可以操作的对象(例如,更改/添加属性),然后转换回json字符串。

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:

问题是我从ConvertFrom-Json返回的对象是PSCustomObject类型,它不允许添加属性。所以第3行爆炸了:

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

异常设置“bar”:“无法在此对象上找到属性'bar'。验证该属性是否存在且可以设置。”在行:1 char:1

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

问题:在没有带来太多复杂性的情况下,最好的方法是什么?

1 个解决方案

#1


7  

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

自定义对象允许您添加属性,您只需要正确执行。您需要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:

值得注意的是,根据您的PowerShell版本,Add-Member行可以简化为:

$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.

我不确定哪种语法可以接受,但我知道它在v4中有效,我认为它适用于v3。

#1


7  

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

自定义对象允许您添加属性,您只需要正确执行。您需要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:

值得注意的是,根据您的PowerShell版本,Add-Member行可以简化为:

$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.

我不确定哪种语法可以接受,但我知道它在v4中有效,我认为它适用于v3。