【问题标题】:Parsing json with PowerShell使用 PowerShell 解析 json
【发布时间】:2019-06-11 08:52:00
【问题描述】:

我尝试从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

【问题讨论】:

    标签: json powershell nagios check-mk


    【解决方案1】:

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

    一旦你拥有正确的 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
    

    【讨论】:

    • ($convertedJSON.result |Get-Member | ? MemberType -eq "NoteProperty").Name 效果不错,但 $convertedJSON.result.$(($o.result |Get-Member | ? MemberType -eq "NoteProperty").Name).attributes 返回空响应
    • @OdedRefaeli 请检查一下,我把变量名弄乱了,现在已经更正了。
    • @OdedRefaeli 你能复制我的代码(最后一部分除外)并告诉我你收到了什么吗?不确定我是否遵循您的意思以及您检查的内容,因为您对上次评论不是很准确。
    • 你的代码输出和你写的一样,但是当我对我的 JSON 运行相同的代码时,结果是空的,所以我猜问题出在我的 JSON 输出中。 JSON 输出通过了在线验证工具。无论如何,非常感谢您的支持
    • 检查您的 JSON 与我使用的 JSON 有何不同(可能元素的名称不同,可能某处有两个元素,而示例只有一个),您应该能够弄清楚。如果您遇到困难,请发布问题并记住首先阅读最佳实践:How to Ask。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2018-10-10
    • 2022-11-25
    • 2012-12-07
    • 1970-01-01
    • 2013-08-04
    • 2020-12-30
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多