首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PowerShell解析json

使用PowerShell解析json
EN

Stack Overflow用户
提问于 2019-06-11 16:52:01
回答 1查看 187关注 0票数 0

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

代码语言:javascript
复制
"{"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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-11 17:14:58

您粘贴的JSON是不正确的。它的开头和结尾都不应该有引号。最后还少了一个}。您可以使用任何在线工具like this进行验证。

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

代码语言:javascript
复制
{"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转换过来,您就可以访问它们:

代码语言:javascript
复制
# 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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56539894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档