繁体   English   中英

如何在 PowerShell 中正确地将 HashTable 转换为 JSON?

[英]How do I correctly convert a HashTable to JSON in PowerShell?

我正在使用 PowerShell 向REST API发送POST请求。 请求的正文如下所示:

{
  "title": "game result",
  "attachments": [{
      "image_url": "http://contoso/",
      "title": "good work!"
    },
    {
      "fields": [{
          "title": "score",
          "value": "100"
        },
        {
          "title": "bonus",
          "value": "50"
        }
      ]
    }
  ]
}

现在,以下 PowerShell 脚本产生错误的输出:

$fields = @(@{title='score'; value='100'},@{title='bonus'; value='10'})
$fieldsWrap = @{fields=$fields}
#$fieldsWrap | ConvertTo-Json
$attachments = @(@{title='good work!';image_url='http://contoso'},$fieldsWrap)
$body = @{title='game results';attachments=$attachments}
$json = $body | ConvertTo-Json
$json 

第 3 行(如果未注释)产生正确的输出,但第 7 行产生:

{
  "attachments": [{
      "image_url": "http://contoso",
      "title": "good work!"
    },
    {
      "fields": "System.Collections.Hashtable System.Collections.Hashtable"
    }
  ],
  "title": "game result"
}

它显然写出了HashTable的类型名称,这是我假设的默认ToString()实现。
如何获得正确的输出?

ConvertTo-Json cmdlet 有一个-depth参数,它:

指定包含在 JSON 表示中的包含对象的级别数。 默认值为 2。

因此,您必须增加它:

$body | ConvertTo-Json -Depth 4

这给出了你想要的 JSON 输出:

@{
    title = "game result"    
    attachments =  @(
        @{
            image_url = "http://contoso/"
            title = "good work!"
        },
        @{
            fields = @(
                @{
                    title = "score"
                    value = "100"
                },
                @{
                    title = "bonus"
                    value = "50"
                }
            )
        }
    )
} | ConvertTo-Json -Depth 4

不过,如果没有 Martin Brandl 的建议,就不会奏效 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM