PowerShell:按字段值检索JSON对象

问题描述 投票:39回答:4

考虑这种格式的JSON:

"Stuffs": [
    {
        "Name": "Darts",
        "Type": "Fun Stuff"
    },
    {
        "Name": "Clean Toilet",
        "Type": "Boring Stuff"
    }
]

在PowerShell 3中,我们可以获得一个Stuffs列表:

$JSON = Get-Content $jsonConfigFile | Out-String | ConvertFrom-Json

假设我们不知道列表的确切内容,包括对象的排序,我们如何检索具有Name字段的特定值的对象?

蛮力,我们可以遍历列表:

foreach( $Stuff in $JSON.Stuffs ) { 

但我希望存在一种更直接的机制(类似于C#中的Lync或Lambda表达式)。

json powershell powershell-v3.0
4个回答
52
投票
$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

22
投票

我在这里问了同样的问题:https://stackoverflow.com/a/23062370/3532136它有一个很好的解决方案。我希望它有助于^^。在简历中,您可以使用:

我的案例中的Json文件叫做jsonfile.json

{
    "CARD_MODEL_TITLE": "OWNER'S MANUAL",
    "CARD_MODEL_SUBTITLE": "Configure your download",
    "CARD_MODEL_SELECT": "Select Model",
    "CARD_LANG_TITLE": "Select Language",
    "CARD_LANG_DEVICE_LANG": "Your device",
    "CARD_YEAR_TITLE": "Select Model Year",
    "CARD_YEAR_LATEST": "(Latest)",
    "STEPS_MODEL": "Model",
    "STEPS_LANGUAGE": "Language",
    "STEPS_YEAR": "Model Year",
    "BUTTON_BACK": "Back",
    "BUTTON_NEXT": "Next",
    "BUTTON_CLOSE": "Close"
}

码:

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

$json.psobject.properties.name

输出:

CARD_MODEL_TITLE
CARD_MODEL_SUBTITLE
CARD_MODEL_SELECT
CARD_LANG_TITLE
CARD_LANG_DEVICE_LANG
CARD_YEAR_TITLE
CARD_YEAR_LATEST
STEPS_MODEL
STEPS_LANGUAGE
STEPS_YEAR
BUTTON_BACK
BUTTON_NEXT
BUTTON_CLOSE

感谢mjolinor


14
投票

大卫布拉班特的回答让我得到了我需要的东西,加上这个:

x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type

0
投票

这是我的json数据:

[
   {
      "name":"Test",
      "value":"TestValue"
   },
   {
      "name":"Test",
      "value":"TestValue"
   }
]

Powershell脚本:

$data = Get-Content "Path to json file" | Out-String | ConvertFrom-Json

foreach ($line in $data) {
     $line.name
}
© www.soinside.com 2019 - 2024. All rights reserved.