Nested JSON within PowerShell


i'm having hardest time trying parse nested json string.

thanks in part various posts, i've been able create bastardized solution:

add-type -assembly system.web.extensions $url = "http://localhost/json.aspx" $web_string = (new-object system.net.webclient).downloadstring($url) $json = (new-object system.web.script.serialization.javascriptserializer).deserializeobject($web_string) $body = "" foreach ($message in $json.messages) { write-host "$json.messages(0).row_id" # wanted make sure $message has correct variable }

however, when run script, get:

system.collections.generic.dictionary`2[system.string,system.object].messages(0).row_id system.collections.generic.dictionary`2[system.string,system.object].messages(0).row_id

i can't seem find way loop through each array within $json.messages.  accessing other objects work fine.  missing step?

here's source json:

{"time":"10/25/2012 11:03:03 am",  "nomail":"1",  "messages":[       {"row_id":"23",       "message_from":"root@localhost",       "subject":"test",       "addresses_count":"1"},      {"row_id":"24",       "message_from":"root@localhost",       "subject":"test attachment",       "addresses_count":"1"}             ],  "messages_processed":"2",  "exit_code":"0"}

thanks!


you have couple of issues here. first, you're using () instead of [] array access ( common mistake of vbscript background).second, putting data ref in quotes, you're getting $json evaluated, , else interpreted literal text.

the following appropriate way loop through data:

for($i = 0; $i -lt $json.messages.count;$i++) {$json.messages[$i].row_id}

if still wanted use write-host, this:

for($i = 0; $i -lt $json.messages.count;$i++) { write-host "$($json.messages[$i].row_id)" } 



Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

Edit Group Policy

Hyper-V VM not reaching OS 'Logon' screen

DNS question...