0

我尝试从check_mk with http-api "action=get_all_hosts" 响应中获取所有主机json格式,如下所示:

"{"result": {"some host name": {"attributes": {"tag_Chassis": "Vm", "tag_ServerFamily": "WindowsServer", "tag_criticality": "prod", "tag_Application": "AllApp", "alias": "some alias", "ipaddress": "172.21.x.x", "tag_networking": "lan"}, "hostname": "some host name", "path": "windows"}}" 

现在我尝试格式化响应但没有成功。如何将结果格式化为table所有属性?

4

1 回答 1

2

您粘贴的 JSON 不正确。它的开头和结尾都不应该有引号。而你}最后错过了一个。您可以使用任何这样的在线工具对其进行验证。

一旦你拥有正确的 JSON,它应该是:

{"result": {"some host name": {"attributes": {"tag_Chassis": "Vm", "tag_ServerFamily": "WindowsServer", "tag_criticality": "prod", "tag_Application": "AllApp", "alias": "some alias", "ipaddress": "172.21.x.x", "tag_networking": "lan"}, "hostname": "some host name", "path": "windows"}}}

从 JSON 转换属性后,您可以访问这些属性:

# Convert and save to variable
$convertedJSON = @"
{"result": {"some host name": {"attributes": {"tag_Chassis": "Vm", "tag_ServerFamily": "WindowsServer", "tag_criticality": "prod", "tag_Application": "AllApp", "alias": "some alias", "ipaddress": "172.21.x.x", "tag_networking": "lan"}, "hostname": "some host name", "path": "windows"}}}
"@ | ConvertFrom-Json

# Access attributes
$convertedJSON.result.'some host name'.attributes

# If you don't know the hostname you can find it like this
($convertedJSON.result |Get-Member | ? MemberType -eq "NoteProperty").Name

# List all attributes from your JSON
$convertedJSON.result.$(($convertedJSON.result |Get-Member | ? MemberType -eq "NoteProperty").Name).attributes

# Output will be like this
tag_Chassis      : Vm
tag_ServerFamily : WindowsServer
tag_criticality  : prod
tag_Application  : AllApp
alias            : some alias
ipaddress        : 172.21.x.x
tag_networking   : lan
于 2019-06-11T09:14:58.343 回答