PowerShell:按字段值检索 JSON 对象
问题描述:
考虑采用这种格式的 JSON :
Consider JSON in this format :
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
在 PowerShell 3 中,我们可以获得 Stuffs 列表:
In PowerShell 3, we can obtain a list of Stuffs :
$JSON = Get-Content $jsonConfigFile | Out-String | ConvertFrom-Json
假设我们不知道列表的确切内容,包括对象的排序,我们如何检索具有 Name 字段特定值的对象?
Assuming we don't know the exact contents of the list, including the ordering of the objects, how can we retrieve the object(s) with a specific value for the Name field ?
蛮力,我们可以遍历列表:
Brute force, we could iterate through the list :
foreach( $Stuff in $JSON.Stuffs ) {
但我希望存在更直接的机制(类似于 C# 中的 Lync 或 Lambda 表达式).
But I am hopeful there exists a more direct mechanism ( similar to Lync or Lambda expressions in C# ).
答
$json = @"
{
"Stuffs":
[
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
"@
$x = $json | ConvertFrom-Json
$x.Stuffs[0] # access to Darts
$x.Stuffs[1] # access to Clean Toilet
$darts = $x.Stuffs | where { $_.Name -eq "Darts" } #Darts