首页 > 解决方案 > 无法从 JSON 数据中获取个人详细信息

问题描述

"Ns": {
    "value": [
        {
            "Nname": "exa",
            "SR": [
                {
                    "name": "port1",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 100
                    }
                },
                {
                    "name": "port1_0",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 150
                    }
                },
                {
                    "name": "port2",
                    "properties": {
                        "description": "Allow  1115",
                        "destinationPortRange": "1115",
                        "priority": 100,
                    }
                }
            ]
        }
    ]
}

想要断言优先级和名称的详细信息,但无法做到。

这是我已经实现的:

$Ndetails = templateProperties.parameters.Ns.value.SR
foreach ($Ndata in $Ndetails) {
    $Ndata .properties.destinationPortRange |
        Should -BeExactly @('1111','1111','1115')
} 

如何在 PowerShell 中使用 Pester 解决相同问题?

标签: powershellpester

解决方案


你不需要为此使用foreach。你可以用Select-Object这个。假设您的 JSON与评论中链接的@Mark Wragg 相同

$Json = @'
[{
    "Ns": {
        "value": [{
            "Nname": "exa",
            "SR": [{
                    "name": "port1",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 100
                    }
                },
                {
                    "name": "port1_0",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 150
                    }
                },
                {
                    "name": "port2",
                    "properties": {
                        "description": "Allow  1115",
                        "destinationPortRange": "1115",
                        "priority": 100
                    }
                }
            ]
        }]
    }
}]
'@
 
$t = $Json | ConvertFrom-Json

您的测试文件应如下所示:

$result = $t.Ns.value.SR.properties.destinationPortRange
it 'destinationPortRange matches' {
  $result | Should -BeExactly @('1111','1111','1115')
}

解释

当您比较单个元素时,您的使用foreach不正确(另请注意,我删除了不必要的空间)

$Ndata.properties.destinationPortRange

到数组

| Should -BeExactly @('1111','1111','1115')

您要做的就是像我的示例中那样将数组与数组进行比较。


推荐阅读