Nuno Linhares
Nuno Linhares

Reputation: 10234

Generating JSON from a xml document / Powershell / controlling the array format

I need to read some data from an XML document and then format it as JSON to submit as a POST to a new webservice we're deploying.

While I got most of it to work, I'm not really happy with how the JSON is coming out (I can modify the webservice if needed, so the data format issue I have now is mostly cosmetic).

So... Data source (the xml file):

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

Powershell code reading this/generating the JSON:

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

When output to JSON, I get something like this:

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

The actual question:

Is there a way to keep my PS code generic, but with an output like this instead?

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

Upvotes: 2

Views: 2146

Answers (1)

G42
G42

Reputation: 10019

Doesn't nest the hashtable in an array - remove $configRepository = @()

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

Upvotes: 1

Related Questions