I am finding working with JSON to be much more complex than in other scripting languages, so I can't help but think I am missing an easier way to do this. Given this json.txt
file:
{"key":"value","key1":"a string with lots of spaces"}
I have this working PowerShell code:
$SECRETS_FILE = 'C:\Users\Administrator\Documents\json.txt'
$data = Get-Content -Raw -Path $SECRETS_FILE | ConvertFrom-Json
$data.PSObject.Properties | ForEach-Object {
if ($_.Name -eq "key") {
$value = $_.Value
cli_cmd value=$value
}
}
And I want to do something like this:
$SECRETS_FILE = 'C:\Users\Administrator\Documents\json.txt'
$data = Get-Content -Raw -Path $SECRETS_FILE | ConvertFrom-Json
cli_cmd value=$data["key"]
I have seen many code examples online of referencing keys within a PowerShell object using the $object["key"]
format, but in my case I get nothing. In the above example, $data["key"]
returns null, $data.keys
returns null. I'm at a loss. I can't believe the only way to reference keys within an array is to loop through the entire array doing string matches.