2

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"
    },
]
2
  • $configRepository is an array. How are you converting the array to JSON? Commented Jul 18, 2017 at 14:18
  • Using the standard ConvertTo-Json - this array is part of a much larger array, I posted only some parts relevant to the question at hand... Commented Jul 18, 2017 at 14:20

1 Answer 1

1

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

foreach($attr in ($xml.Configuration.ConfigRepository).attributes)
{
    $configRepository += @{ $attr.Name = $attr.Value} 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, that simple! Thank you SO much. - I'll accept it when I can (apparently need to wait a few more minutes).
@NunoLinhares No problem! Reg simplicity, PowerShell is nice like that. Previously, another StackOverflow soul had the opposite problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.