Skip to content

Instantly share code, notes, and snippets.

@lamw
Created April 2, 2014 05:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamw/9928202 to your computer and use it in GitHub Desktop.
Save lamw/9928202 to your computer and use it in GitHub Desktop.
Parsing JSON in PowerShell using ConvertFrom-Json
$json = @"
{"A": {"property1": "value1", "property2": "value2"}, "B": {"property1": "value3", "property2": "value4"}}
"@
$parsed = $json | ConvertFrom-Json
foreach ($line in $parsed | Get-Member) {
echo $parsed.$($line.Name).property1
echo $parsed.$($line.Name).property2
}
@RamblingCookieMonster
Copy link

Hello!

I don't know JSON so I did this:

@(
    [pscustomobject]@{A=$([pscustomobject]@{property1= 'value1';property2='value2'})}
    [pscustomobject]@{B=$([pscustomobject]@{property1='value3';property2='value4'})}
    ) | ConvertTo-Json

This produces:

[
    {
        "A":  {
                  "property1":  "value1",
                  "property2":  "value2"
              }
    },
    {
        "B":  {
                  "property1":  "value3",
                  "property2":  "value4"
              }
    }
]

Seems like an odd object model - this might be the basis behind the difficulty working with the data, rather than PowerShell. Did you mean something like this?

[
    {
        "property1":  "value1",
        "property2":  "value2"
    },
    {
        "property1":  "value3",
        "property2":  "value4"
    }
]

Which produces this:

$parsed = @"
[
    {
        "property1":  "value1",
        "property2":  "value2"
    },
    {
        "property1":  "value3",
        "property2":  "value4"
    }
]
"@ | convertfrom-json

foreach($line in $parsed){
   $line.property1
   $line.property2
}

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment