【问题标题】:Generating JSON from a xml document / Powershell / controlling the array format从 xml 文档/Powershell/控制数组格式生成 JSON
【发布时间】:2017-12-23 11:16:17
【问题描述】:

我需要从 XML 文档中读取一些数据,然后将其格式化为 JSON,以作为 POST 提交到我们正在部署的新 Web 服务。

虽然我大部分可以工作,但我对 JSON 的输出方式并不满意(如果需要,我可以修改 web 服务,所以我现在遇到的数据格式问题是主要是化妆品)。

所以...数据源(xml文件):

<ConfigRepository ServiceUri="http://somemachine"
                  ConnectionTimeout="10000"
                  CacheEnabled="true"
                  CacheExpirationDuration="600"
                  ServiceMonitorPollDuration="10" />

Powershell 代码读取/生成 JSON:

$configRepository = @()
foreach($attr in ($xml.Configuration.ConfigRepository).attributes)
{
    $configRepository += @{ $attr.Name = $attr.Value} 
}

当输出到 JSON 时,我得到如下信息:

"ConfigRepository":  [
    {
        "CacheEnabled":  "true"
    },
    {
        "CacheExpirationDuration": "600"
    },
    {
        "ConnectionTimeout":  "10000"
    },
    {
        "ServiceMonitorPollDuration":  "10"
    },
    {
        "ServiceUri":  "http://somemachine"
    },
]     

实际问题:

有没有办法让我的 PS 代码保持通用,但使用这样的输出?

"ConfigRepository":  [
    {
        "CacheEnabled":  "true"
        "CacheExpirationDuration": "600"
        "ConnectionTimeout":  "10000"
        "ServiceMonitorPollDuration":  "10"
        "ServiceUri":  "http://somemachine"
    },
]

【问题讨论】:

  • $configRepository 是一个数组。您如何将数组转换为 JSON?
  • 使用标准的ConvertTo-Json - 这个数组是一个更大的数组的一部分,我只发布了一些与手头问题相关的部分......

标签: json xml powershell


【解决方案1】:

不在数组中嵌套哈希表 - 删除 $configRepository = @()

foreach($attr in ($xml.Configuration.ConfigRepository).attributes)
{
    $configRepository += @{ $attr.Name = $attr.Value} 
}

【讨论】:

猜你喜欢
  • 2014-02-15
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多