如何使用PowerShell从json响应中获取单个值
我有以下json。我只想从下面的响应中提取“id”中的值41:“41”。假设我不知道该值是什么,我如何提取该单个值,将其分配给变量并查看输出如何使用PowerShell从json响应中获取单个值,json,powershell,extract,Json,Powershell,Extract,我有以下json。我只想从下面的响应中提取“id”中的值41:“41”。假设我不知道该值是什么,我如何提取该单个值,将其分配给变量并查看输出 { "page": { "offset": 0, "total": 36, "totalFilter": 1 }, "list": [ { "id": "41",
{
"page": {
"offset": 0,
"total": 36,
"totalFilter": 1
},
"list": [
{
"id": "41",
"type": "ATBR",
"hostName": "AAMS",
"userId": "",
"userName": "",
"status": "CONNECTED",
"poolName": "",
"fullyQualifiedHostName": "-",
"updatedBy": "mscr",
"updatedOn": "2020-06-24T23:28:11.239894Z",
"botAgentVersion": "9.0"
}
]
}
到目前为止,我已经有了下面的内容,但我不知道如何只获取单个值
$json = @"
{
"page": {
"offset": 0,
"total": 36,
"totalFilter": 1
},
"list": [
{
"id": "41",
"type": "ATBR",
"hostName": "AAMS",
"userId": "",
"userName": "",
"status": "CONNECTED",
"poolName": "",
"fullyQualifiedHostName": "-",
"updatedBy": "mscr",
"updatedOn": "2020-06-24T23:28:11.239894Z",
"botAgentVersion": "9.0"
}
]
}
"@
$x = $json | ConvertFrom-Json
$x.list[0]
$id = $x.list | Where { $_.list -eq "id" }
我的当前输出结果如下。我只想从中提取41条
id : 41
type : ATBR
hostName : AAMS
userId :
userName :
status : CONNECTED
poolName :
fullyQualifiedHostName : -
updatedBy : mscr
updatedOn : 2020-06-24T23:28:11.239894Z
botAgentVersion : 9.0
非常感谢您的帮助-提前感谢一旦您将JSON转换为对象,您就可以使用
Where object
或Where
来过滤列表
数组元素,该数组元素包含id
,且具有非空值和非空值。然后使用成员访问操作符
检索id
属性的值
$json = @"
{
"page": {
"offset": 0,
"total": 36,
"totalFilter": 1
},
"list": [
{
"id": "41",
"type": "ATBR",
"hostName": "AAMS",
"userId": "",
"userName": "",
"status": "CONNECTED",
"poolName": "",
"fullyQualifiedHostName": "-",
"updatedBy": "mscr",
"updatedOn": "2020-06-24T23:28:11.239894Z",
"botAgentVersion": "9.0"
}
]
}
"@
$x = $json | ConvertFrom-Json
$id = ($x.list | Where id).id
使用whereid
基本上检查[boo]$x.list.id
是否返回true
。因此,如果使用Where userId
,它将不会返回任何内容,因为[bool]$x.list.userId
的计算结果为false
您也可以使用
Select Object
检索id
值:
$id = $x.list | Where id | Select-Object -Expand id
请注意,如果
list
中有多个对象(因为它是一个数组)包含带有值的id
,将返回多个id
值。$id=($x.list | where id).id
。