1

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
DrStrangepork
  • 2,955
  • 2
  • 27
  • 33
  • 1
    While I've closed this as a duplicate, I want to point out that since you tagged the question with [tag:powershell-core], you should look at [this newer answer in particular](https://stackoverflow.com/a/48992740/3905079), which shows that in PowerShell Core (v6+), an `-AsHashtable` parameter was added to `ConvertFrom-Json` which does exactly what you want. – briantist Jun 19 '19 at 20:47
  • I did try that, and it does not appear to do what I want. `$data["key"]` translates to `"System.Collections.Hashtable[key]"` rather than the value of that key – DrStrangepork Jun 19 '19 at 20:54
  • I can't reproduce that behavior. In PowerShell Core, this works as expected: `$data = '{"key":"value","key1":"a string with lots of spaces"}' | ConvertFrom-Json -AsHashtable ; $data["key"]` – briantist Jun 19 '19 at 21:02
  • 1
    @DrStrangepork Looks like PowerShell interprets `value=$data["key"]` as a string. Try `$value = $data['key']; cli_cmd value=$value` or `cli_cmd "value=$($data['key'])"` instead. – Ansgar Wiechers Jun 20 '19 at 09:09
  • Ansgar Wiechers' comment is correct - `cli_cmd "value=$($data['key'])"` fixed the problem. I'd like this question reopened so I can give them credit. – DrStrangepork Jun 20 '19 at 13:18
  • What I outlined is a common problem with the interpolation of variables in strings. Even if someone re-opened the question it would still be a duplicate, though perhaps of a different question (like [this one](https://stackoverflow.com/q/9196525/1630171)). – Ansgar Wiechers Jun 21 '19 at 09:57

0 Answers0