根据条件使用 PowerShell 从 JSON 中提取值
Extract Value from JSON Using PowerShell based on condition
我在变量 $releaseDefinitions 中捕获了 JSON 响应。有了这个,当我使用 powershell 在“环境”标签下将“名称”作为“STAGE1-PG-DB”传递时,我想将“ID”提取为“4598”。
非常感谢对此的任何帮助。
{
"id": 516,
"environments": [
{
"id": 4598,
"releaseId": 516,
"name": "STAGE1-PG-DB",
"status": "notStarted",
},
{
"id": 4599,
"releaseId": 516,
"name": "STAGE2-PG-DB",
"status": "notStarted",
},
{
"id": 4600,
"releaseId": 516,
"name": "STAGE3-PG-DB",
"status": "notStarted",
}
]
}
我相信您要求获取名称为“STAGE1-PG-DB”的 JSON 数组对象。
根据你提供的信息,你会做这样的事情(见我的 in-line 评论)
$releaseDefinitions = Get-Content -Path $inputFileName -Raw | ConvertFrom-Json
# use dot-notation to get the entire Environments array
# pipe the array through using the pipe character
# filter through the array where the key (Name) is equal to your value (STAGE1-PG-DB)
$releaseDefinitions.environments | Where-Object {$_.name -eq "STAGE1-PG-DB"}
我在变量 $releaseDefinitions 中捕获了 JSON 响应。有了这个,当我使用 powershell 在“环境”标签下将“名称”作为“STAGE1-PG-DB”传递时,我想将“ID”提取为“4598”。
非常感谢对此的任何帮助。
{
"id": 516,
"environments": [
{
"id": 4598,
"releaseId": 516,
"name": "STAGE1-PG-DB",
"status": "notStarted",
},
{
"id": 4599,
"releaseId": 516,
"name": "STAGE2-PG-DB",
"status": "notStarted",
},
{
"id": 4600,
"releaseId": 516,
"name": "STAGE3-PG-DB",
"status": "notStarted",
}
]
}
我相信您要求获取名称为“STAGE1-PG-DB”的 JSON 数组对象。 根据你提供的信息,你会做这样的事情(见我的 in-line 评论)
$releaseDefinitions = Get-Content -Path $inputFileName -Raw | ConvertFrom-Json
# use dot-notation to get the entire Environments array
# pipe the array through using the pipe character
# filter through the array where the key (Name) is equal to your value (STAGE1-PG-DB)
$releaseDefinitions.environments | Where-Object {$_.name -eq "STAGE1-PG-DB"}