2017-07-18 39 views
2

我需要从XML文档读取一些数据,然后将其格式化为JSON,以便作为POST提交给我们正在部署的新Web服务。虽然我得到了大多数它工作,我对JSON如何出来(我可以修改web服务,如果需要的话,所以我现在的数据格式问题大多是化妆品)并不是很满意。从xml文档/ Powershell生成JSON /控制阵列格式

所以...数据源(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" 
    }, 
] 
+0

'$ configRepository'是一个数组。你如何将数组转换为JSON? –

+0

使用标准的'ConvertTo-Json' - 这个数组是一个更大的数组的一部分,我只发布了一些与手头问题相关的部分... –

回答

1

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

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

哇,那很简单!非常感谢。 - 当我可以的时候我会接受它(显然需要等待几分钟)。 –

+0

@NunoLinhares没问题!注册简单,PowerShell很好。 [以前,另一个StackOverflow灵魂有相反的问题](https://stackoverflow.com/questions/44433728/powershell-to-form-correctly-formatted-json-for-calendar-entry/44433946) – gms0ulman