PowerShell: get JSON object by variable

$json = ConvertFrom-Json "{key:true}"
$key = "key"
Write-Host $json[$key]

I would like it to be true, but it is not. I know that $json.keywill work. It can be done?

+4
source share
2 answers

If you know what $json.keywill work, then why are you switching from dots to square brackets? All this will work:

$json = ConvertFrom-Json "{key:true}"
$key = "key"

Write-Host $json.$key
Write-Host $json.$($key)
Write-Host $json."$key"
+6
source

You can reference it using dot notation with your variables.

$json.$key

So, in your Write-Host you will need a subexpression if you used quotes in your hosting

Write-Host "Key is: $($json.$key)"

You tried to use array notation and returned null.

+2
source

All Articles