Reputation: 2857
I want to read JSON out of a file and convert it into an array of strings made from the concatenation of two properties.
So far I've got this:
$packageCache = Get-Content $pathtojsonfile | ConvertFrom-Json | %{$($_.Key) + "-" + $($_.Value)}
Write-Output $packageCache
The problem is that it ends up creating an array containing the Id values and Version values as completely different items in the array.
It ends up looking like this:
key1
key2
value1
value2
What have I got wrong?
Update: The JSON looks like this:
[{ "Key":"key1", "Value":"value1"},{"Key":"key2", "Value":"value2"}]
The expected result is this:
key1-value1
key2-value2
The code as posted is all there is. Yes, it's part of a script.
Upvotes: 1
Views: 3562
Reputation: 2857
CodedBeard beat me to it, but...
I was totally on the wrong track here. Apparently ConvertFrom-Json retuns an Object[]. So, I was just iterating over the single item and not getting anywhere.
If I unroll the returned array, everything starts to work.
($packageCache = Get-Content $pathtojsonfile | ConvertFrom-Json) | %{$($_.Key) + "-" + $($_.Value)}
Note the ( and ) around the first part of the command.
Upvotes: 0
Reputation: 912
It's the final pipe bind that is messing you up, just change it to:
$json = Get-Content $pathtojsonfile | ConvertFrom-Json
$packageCache = $json |% {"$($_.Key)-$($_.Value)"}
$packageCache
key1-value1
key2-value2
Incidentally, I'll also point out that the +
signs are not necessary, just wrap the whole thing in "
as shown above.
Upvotes: 1