Arun
Arun

Reputation: 3680

Read JSON and Iterate in Powershell

I have a JSON file where I have maintained few settings. Below is my JSON File

{

    "1":{
        "foundation_name":"Pre-Prod1",
        "api_url": "https://sys1.com"
    },
    "2":{
        "foundation_name":"Pre-Prod2",
        "api_url": "https://sys-2.com"
    },
    "3":{
        "foundation_name":"Prod1",
        "api_url": "https://sys5.com"
    }
}

And I am trying to read this JSON and PRINT it in my screen by Iterating it. Below is my Powershell script

Function FoundationSettings {
    Write-Host 'Reading from File'
    $foundations = Get-Content ".\foundations.json" -Raw | ConvertFrom-Json
    Write-Host $foundations
    return $foundations
}

Function DisplayFoundations {
    $foundations = FoundationSettings
    foreach ($foundation in $foundations) {
        Write-Host 'here ..'
        Write-Host $foundation.foundation_name
    }

}

But it just prints this way

Reading from File
@{1=; 2=; 3=}
here ..

How to solve it ? I need to parse the JSON and at my demand i would have get the api_url data and foundation_name

Upvotes: 0

Views: 242

Answers (2)

Nas
Nas

Reputation: 1263

Access the value of the underlying properties:

Function DisplayFoundations {
    $foundations = FoundationSettings
    foreach ($foundation in $foundations.psobject.Properties.Value) {
        Write-Host 'here ..'
        Write-Host $foundation.foundation_name
    }
}

Upvotes: 1

Paweł Dyl
Paweł Dyl

Reputation: 9143

If that format is unchangeable, you can use:

$obj = @'
{

    "1":{
        "foundation_name":"Pre-Prod1",
        "api_url": "https://sys1.com"
    },
    "2":{
        "foundation_name":"Pre-Prod2",
        "api_url": "https://sys-2.com"
    },
    "3":{
        "foundation_name":"Prod1",
        "api_url": "https://sys5.com"
    }
}
'@ | ConvertFrom-Json

$listOfObjects = ($obj | Get-Member -MemberType NoteProperty).Name | % { $obj.$_ }

If you can change it, use JSON array where array is more appropriate:

$listOfObjects | ConvertTo-Json

Which gives:

[
    {
        "foundation_name":  "Pre-Prod1",
        "api_url":  "https://sys1.com"
    },
    {
        "foundation_name":  "Pre-Prod2",
        "api_url":  "https://sys-2.com"
    },
    {
        "foundation_name":  "Prod1",
        "api_url":  "https://sys5.com"
    }
]

Upvotes: 1

Related Questions