1

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.

3
  • So us a sample JSON to start so we can reproduce the issue in the even it is not obvious Commented Apr 6, 2016 at 23:21
  • 1
    I can't see how that can be your code, the only outputs that make sense to me would be errors (file doesn't exist, isn't valid JSON, etc.) or strings containing -, or at least - lines at the end of the output. I have to guess you're working in the shell and didn't run the lines in the same order, or didn't run those exact lines, or you're in a script and one line is in a function in another scope, or something like that...? Commented Apr 6, 2016 at 23:32
  • Also you probably want .Keys and .Values (with 's' at the end), but that doesn't change my previous confusion. Commented Apr 6, 2016 at 23:35

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was literally typing up my own answer as yours popped in. I didn't realize that ConvertFrom-Json returns a System.Object[]. This means that I kept iterating over a single Object[]. The one line variation is just to surround the first part with ( and ). Good catch!
Good point on the 1 line version, should have posted that instead :)
0

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.

Comments

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.