powershell - 无法从 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 解决相同问题?
解决方案
你不需要为此使用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')
您要做的就是像我的示例中那样将数组与数组进行比较。
推荐阅读
- nearprotocol - 交易/操作的气体限制是多少?
- c++ - 从 CMake 在 Eigen 中设置最大静态对齐
- excel - 如何使循环检查,总结单元格值并停在正确的位置
- c - c中的变量随机改变值
- racket - 如何在 Racket 中制作 HTML 表格边框
- vb.net - 如何计算已在 VB.NET 中的 datagridview 中检查的复选框
- microservices - jhipster 注册中心/控制中心向网关应用程序发送管理请求导致 401 未授权
- html - 为什么不使用填充作为显示?
- python - 我可以将 python 服务器与 kotlin 客户端连接起来吗?
- java - 我如何检测是否有人输入了错误的 otp