Reputation: 1
How to add "data" : [
block when using $var | convertTo-Json
?
The actual output of $var
is just a object with some properties which is then converted to json using the command convertTo-Json
.
Here is what I get:
[
{
"controllerID": "0",
"DiskID": "0:1:0",
"cName": "PERCS130",
},
{
"controllerID": "0",
"DiskID": "0:1:1",
"cName": "PERCS130",
}
]
But I need something like this:
{
"data": [
{
"controllerID": "0",
"DiskID": "0:1:0",
"cName": "PERCS130",
},
{
"controllerID": "0",
"DiskID": "0:1:1",
"cName": "PERCS130",
}
]
}
Upvotes: 0
Views: 196
Reputation: 27606
Here's a way to make a new object with a data array property containing $var:
$newvar = [pscustomobject]@{data = $var}
$newvar
data
----
{@{controllerID=0; DiskID=0:1:0; cName=PERCS130}, @{controllerID=0; DiskID=0:1:1; cName=PERCS130}}
Then you can do convertto-json:
$newvar | convertto-json
{
"data": [
{
"controllerID": "0",
"DiskID": "0:1:0",
"cName": "PERCS130"
},
{
"controllerID": "0",
"DiskID": "0:1:1",
"cName": "PERCS130"
}
]
}
Or with the json in a file and if you have jq. Same output.
get-content file.json | jq '{data:.}'
Upvotes: 0
Reputation: 61218
The JSON you show is invalid because of the comma's after "cName": "PERCS130"
. This is probably because you have stripped stuff out here.
What you need to do is create a new json, where a new element data
contains the current json as array:
$json = @"
[
{
"controllerID": "0",
"DiskID": "0:1:0",
"cName": "PERCS130"
},
{
"controllerID": "0",
"DiskID": "0:1:1",
"cName": "PERCS130"
}
]
"@ | ConvertFrom-Json
$newjson = @{'data' = @($json)}
$newjson | ConvertTo-Json -Depth 3 # you may need to up the Depth value
Result:
{ "data": [ { "controllerID": "0", "DiskID": "0:1:0", "cName": "PERCS130" }, { "controllerID": "0", "DiskID": "0:1:1", "cName": "PERCS130" } ] }
PowerShell does not produce 'pretty' json. If you need to convert it to properly spaced json, see my function Format-Json
Upvotes: 1