given processing following $json variable, how grab each server id (i.e. 215d1109-216d-48c3-af8e-998bb9bc3ca0 , 440cf918-3ee0-4143-b289-f63e1d2000e6 in case) , put array?
right $obj.servers.id returns nothing (as expected), $obj.servers.id[0] returns error message.
clear [system.reflection.assembly]::loadwithpartialname("system.web.extensions") | out-null $json = ' { "servers": [ { "admin_password": "qpyu66rkxmnk", "id": "215d1109-216d-48c3-af8e-998bb9bc3ca0", "links": [ { "href": "http://openstack.example.com/v3/servers/<id>", "rel": "self" }, { "href": "http://openstack.example.com/servers/<id>", "rel": "bookmark" } ] }, { "admin_password": "wfksh3gttsep", "id": "440cf918-3ee0-4143-b289-f63e1d2000e6", "links": [ { "href": "http://openstack.example.com/v3/servers/<id>", "rel": "self" }, { "href": "http://openstack.example.com/servers/<id>", "rel": "bookmark" } ] } ] } ' $ser = new-object system.web.script.serialization.javascriptserializer $obj = $ser.deserializeobject($json) $obj.servers.id; please note using powershell 2.0.
you're misunderstanding structure of data. $obj.servers array 2 fields, each of contains dictionary, not object containing array id. need make index access this:
$obj.servers[0].id $obj.servers.id[0] throw error, because array object $obj.servers doesn't have property id, in powershell v2 $obj.servers.id returns $null, , index access on null array fails (as you'd expect).
demonstration:
ps c:\> [void][reflection.assembly]::loadwithpartialname('system.web.extensions') $json = @' ... '@ ps c:\> $ser = new-object web.script.serialization.javascriptserializer ps c:\> $obj = $ser.deserializeobject($json) ps c:\> $obj.servers.gettype().fullname system.object[] ps c:\> $obj.servers.id -eq $null true ps c:\> $obj.servers[0].gettype().name dictionary`2 ps c:\> $obj.servers[0] | format-table -autosize key value --- ----- admin_password qpyu66rkxmnk id 215d1109-216d-48c3-af8e-998bb9bc3ca0 links {system.collections.generic.dictionary`2[system.str... ps c:\> $obj.servers[0].id 215d1109-216d-48c3-af8e-998bb9bc3ca0 to extract ids pipe array foreach-object loop echo id property:
ps c:\> $ids = $obj.servers | % { $_.id } ps c:\> $ids 215d1109-216d-48c3-af8e-998bb9bc3ca0 440cf918-3ee0-4143-b289-f63e1d2000e6
Comments
Post a Comment