4
$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?

2 Answers 2

13

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"
Sign up to request clarification or add additional context in comments.

1 Comment

key is read from somewhere else. $json.$key works nicely... I had no idea PS could understand that. Thanks!
2

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.

1 Comment

Thanks for the downvote.. really. It let me know I made a mistake in typing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.