Vaccano Vaccano - 3 months ago 13
PowerShell Question

Get a json value using powershell 2.0

I know this is super easy using powershell 3.0. Alas I am using v2 for now.

So, say I have a json file (config.json) that looks like this:

{
"environment": "dev",
"SomeKey": "SomethingElse",
"AnotherKey": "More Here",
"stuff": {
"More": "Stuff Here"
},
// More stuff here
}


Is there a way I can get the value of "AnotherKey" using powershell (v2.0)?

Update:

It is probably safe to say that in this case,
"AnotherKey":
will not appear in the file anywhere else.

Answer

Tested from the link I gave in the comment:

function ConvertFrom-Json20([object] $item){ 
    add-type -assembly system.web.extensions
    $ps_js=new-object system.web.script.serialization.javascriptSerializer

    #The comma operator is the array construction operator in PowerShell
    return ,$ps_js.DeserializeObject($item)
}

$json = @"
{
    "environment": "dev",
    "SomeKey": "SomethingElse",
    "AnotherKey":  "More Here",
    "stuff": {
        "More": "Stuff Here"
    }     
}
"@

$a = ConvertFrom-Json20 $json

Result is:

$a.AnotherKey
More Here

Notice I had to edit you json example (extra comma + removed the commented out code)

Comments