Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell : retrieve JSON object by variable value

Tags:

powershell

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

I'd like that to print true but it doesn't. I know $json.key would work. Can this be done?

like image 937
Laoujin Avatar asked Dec 08 '22 03:12

Laoujin


2 Answers

If you know that $json.key would work, then why you're switching from dot to square brackets? All these will work:

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

Write-Host $json.$key
Write-Host $json.$($key)
Write-Host $json."$key"
like image 127
AdamL Avatar answered Dec 15 '22 10:12

AdamL


You could be referencing it using dot notation with your variables.

$json.$key

So in your Write-Host you would need a subexpression if you used quotes in your write-host

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

You were trying to use array notation and returning null.

like image 45
Matt Avatar answered Dec 15 '22 10:12

Matt