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

标签 json powershell

我正在使用PowerShell将POST请求发送到REST API。请求的主体如下所示:

{
  "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参数:

Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.


因此,您必须增加它:
$body | ConvertTo-Json -Depth 4

关于json - 如何在PowerShell中将HashTable正确转换为JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38012564/

相关文章:

java - GSON解析改变json数据

powershell - 从脚本位置 powershell 创建 zip

git - 克隆项目时权限被拒绝

javascript - 获取给定 id 的 Youtube 标题

c# - 发出 Json 对象和 C#

java - 使用java有条件地获取json数据

powershell - 将环境变量转成数组

git - 如何在powershell中使用stdin来使用git commit-tree?

Azure功能应用程序powershell触发两次/三次

java - JSON 响应表示更新的变量为空