PowerShell: Retrieve the JSON object by variable value

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

I want it to be printed, but it is not the case. I know that $json.key will work. Can it be done?

If you know that $json.key works, then why switch from dot to square brackets?
All of these are valid:

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

Write-Host $json.$key
Write-Host $json.$($key)
Write-Host $json."$key"

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

I want it to be printed, but it is not the case. I know that $json.key will work. Can it be done?

If you know that $json.key works, then why switch from dot to square brackets?
All of these are valid:

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

Write-Host $json.$key
Write-Host $json.$($key)
Write-Host $json."$key"

Leave a Comment

Your email address will not be published.