[英]Read JSON and Iterate in Powershell
我有一个JSON
文件,其中维护了一些设置。 以下是我的JSON文件
{
"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"
}
}
我正在尝试读取此JSON
并通过迭代在屏幕上PRINT
它。 以下是我的Powershell
脚本
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
}
}
但是它只是这样打印
Reading from File
@{1=; 2=; 3=}
here ..
怎么解决呢? 我需要解析JSON,并根据需要获得api_url
数据和foundation_name
如果该格式不可更改,则可以使用:
$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.$_ }
如果可以更改它,请使用JSON数组,其中array更合适:
$listOfObjects | ConvertTo-Json
这使:
[
{
"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"
}
]
访问基础属性的值:
Function DisplayFoundations {
$foundations = FoundationSettings
foreach ($foundation in $foundations.psobject.Properties.Value) {
Write-Host 'here ..'
Write-Host $foundation.foundation_name
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.