I’m looking to create JSON output from a Powershell script but as i always do… i’m struggling with formatting
The format I’m looking to create is for a system called PRTG and their example is:
{
"prtg": {
"result": [{
"channel": "First channel",
"value": 10
},
{
"channel": "Second channel",
"value": 20
}
]
}
}
in Powershell i have come up with this which i know isn’t right as the IDE is giving me red exclamation marks
$body = @(
"prtg" = @{
"result" = @(
{
channel = "Channel 1"
value = $val1
},
{
channel = "Channel 2"
value = $val2
}
)
}
)
ConvertTo-Json -InputObject $body
Can someone kindly help with where i’m going wrong please, most likely very wrong
Thanks
Jamie
Don’t make it hard on yourself, let powershell do the work
$body = @{
prtg = @{
result = @(
@{
Channel = "Channel 1"
value = $val1
},
@{
channel = "Channel 2"
value = $val2
}
)
}
} | ConvertTo-Json -Depth 4
{
"prtg": {
"result": [
{
"value": 10,
"Channel": "Channel 1"
},
{
"value": 20,
"channel": "Channel 2"
}
]
}
}
As you can see hash tables don’t care about order by default. I wouldn’t imagine it mattering for an api call but just in case here’s how you can maintain the properties order
$body = @{
prtg = @{
result = @(
[ordered]@{
Channel = "Channel 1"
value = $val1
},
[ordered]@{
channel = "Channel 2"
value = $val2
}
)
}
} | ConvertTo-Json -Depth 4
Just remember it’s easier to create hash tables and then convert that to json in powershell. You can build up the object too, like this
$body = @{
prtg = @{}
}
$body.prtg = @{
Result = @{}
}
$body.prtg.Result = @{
Channel = "Channel 1"
value = $val1
},
@{
Channel = "Channel 2"
value = $val2
}
$body | ConvertTo-Json -Depth 3
2 Likes
Thank you for much for your help, the code you provided worked perfectly and the explanations really helped.
I actually found a blog post about this which really helped and i got to this
$body = @{
prtg = @{
result = @(
@{
channel = "Channel 1"
value = 1
},
@{
channel = "Channel 2"
value = 2
}
)
}
}
$json = ConvertTo-Json -InputObject $body
However prtg wasn’t happy and it’s because the output was formatting like:
{
"prtg": {
"result": [
"System.Collections.Hashtable",
"System.Collections.Hashtable"
]
}
}
So i guess there is a difference between piping to convertto-json and using the convertto command?
Maybe the depth parameter…
Ah yes, adding depth fixed it
Thank you very much for your help, and the breakdown
$body = @{
prtg = @{}
}
$body.prtg = @{
Result = @{}
}
$body.prtg.Result = @{
Channel = "Channel 1"
value = $val1
},
@{
Channel = "Channel 2"
value = $val2
}
$body | ConvertTo-Json -Depth 3
Regards,
Jamie