5

I'm starting to learn Powershell and I'm currently trying to read in a JSON file.

Here is my JSON file (named 'versions.json'):

{
    "versions": {
        "1.0.0": {
            "Component1": "1.0.0",
            "Component2": "1.0.0",
            "Component3": "1.0.0",
        },
        "2.0.0": {
            "Component1": "2.0.0",
            "Component2": "2.0.0",
            "Component3": "2.0.0"
        }
    }
}

I would like to read in this JSON file and print out the versions and what they consist of. For example, 1.0.0 consists of Component 1 at 1.0.0, Component 2 at 1.0.0, and Component 3 at 1.0.0.

I'm currently reading in the JSON file with this Powershell line:

$json = (Get-Content "versions.json" -Raw) | ConvertFrom-Json

Now, I want to iterate through $json and print out its data. I'm currently using this:

foreach($v in $json.versions) {
    echo "Data: $v"
}

But, when I run my Powershell script, it prints:

Data: @{1.0.0=; 2.0.0=}

Is this the proper output? I was expecting to at least see two entries for 1.0.0 and 2.0.0. This feels like it may be a syntax issue but I am unsure. I am using Powershell version 5.

2
  • The '$v' was missing in the original post. I've fixed it. Commented Aug 7, 2017 at 20:26
  • 1
    It's not a collection, which is why you can't iterate over it. If you do $json.versions | get-member you'll see 1.0.0 and 2.0.0 are the properties of a single item. Commented Aug 7, 2017 at 20:30

1 Answer 1

3

After using ConvertFrom-Json you have a PowerShell object which is a single item that has a versions property which has two sub-properties 1.0.0 and 2.0.0. Your ForEach is attempting to iterate them like a collection, but its just a single object.

However you can iterate over the properties as follows to get the result I think you wanted:

 ($Json.versions.psobject.properties) | foreach-object { "Data: $($_.name)" }
Sign up to request clarification or add additional context in comments.

5 Comments

When I run your code snippet, I get "cmdlet ForEach-Object at command pipeline position 1. Supply values for the following parameters: Process[0]"
Are you sure you copied it correctly? That suggests you're missing the scriptblock part (this bit { "Data: $($_.name)" })
Hmm, I guess everything has to be on a single line (I moved the "Data:" portion and the brackets down. Now when I run it, I get "Data: " - nothing is there.
Just the opening { needs to be on the same line, you can then add line breaks if you want to.
My fault - had a typo in my file. Your snippet works properly. I've accepted your answer.

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.