I need to convert a CSV to a particular JSON format but having trouble.
I currently have created the below powershell code which takes a CSV file with multiple columns and data for each column
enter code here $csvcontent = get-content "C:\tmp\vmfile.csv" | select -Skip 1
$Json =foreach($line in $csvcontent){
$obj = [PSCustomObject]@{
description = ($line -split ",")[0] -replace "`""
requestedFor = ($line -split ",")[1] -replace "`""
VMs = @{
vmType = $(($line -split ",")[5] -replace "`"");
environment = $(($line -split ",")[6] -replace "`"");
vmdescription = $(($line -split ",")[7] -replace "`"");
function = $(($line -split ",")[8] -replace "`"");
datacenter = $(($line -split ",")[9] -replace "`"");
Size = $(($line -split ",")[10] -replace "`"");
adDomain = $(($line -split ",")[11] -replace "`"");
Hostname = $(($line -split ",")[12] -replace "`"")
}
ExtraDisks = @{
VolumeName = $(($line -split ",")[14] -replace "`"");
VolumeLetter = $(($line -split ",")[15] -replace "`"");
Size = $(($line -split ",")[16] -replace "`"")
}
}
$obj | ConvertTo-Json
}
$json -replace '(?<=:\s+){','[ {' -replace '(?<="\s+)}','} ]'
This then generates the following json file which is not what i need as i want it all to come under the VM brackets not have a separate one for each VM
enter code here
{
"requestedFor": "John Doe",
"VMs": {
"Size": "Medium",
"datacenter": "DC1",
"environment": "dev",
"adDomain": "mydomain.com",
"vmType": "Windows Server",
"vmdescription": "VM Build1",
"function": "app",
"Hostname": "VMBuild1"
},
"ExtraDisks": {
"VolumeLetter": "G",
"Size": "10",
"VolumeName": "Logs"
}
}
{
"requestedFor": "John Doe",
"VMs": {
"Size": "Medium",
"datacenter": "DC2",
"environment": "prod",
"adDomain": "mydomain.com",
"vmType": "Windows Server",
"vmdescription": "VM Build2",
"function": "app",
"Hostname": "VMBuild2"
},
"ExtraDisks": {
"VolumeLetter": "E",
"Size": "50",
"VolumeName": "Data"
}
}
but what i need it to look like this
enter code here
{
"requestedFor": "John Doe",
"VMs": [ {
"vmType": "Windows Server",
"environment": "dev",
"description": "VMBuild1",
"function": "app",
"datacenter": "DC1",
"size": "Medium",
"adDomain": "mydomain.com",
"Hostname": "VMBuild1",
"ExtraDisks": [ {
"VolumeName": "Logs",
"VolumeLetter": "G",
"VolumeSize": 10
}
]
},
{
"vmType": "Windows Server",
"environment": "prod",
"description": "VMBuild2",
"function": "app",
"datacenter": "DC2",
"size": "Medium",
"adDomain": "mydomain.com",
"Hostname": "VMBuild2",
"ExtraDisks": [ {
"VolumeName": "Data",
"VolumeLetter": "E",
"VolumeSize": 50
}
]
}
]
}
Here is the CSV file contents
vmType environment description function datacenter Size adDomain Hostname VolumeName VolumeLetter VolumeSize
Windows Server dev VMBuild1 app DC1 Medium mydomain.com VMBUILD1 Logs G 10
Windows Server prod VMBuild2 app DC2 Medium mydomain.com VMBUILD2 Data E 50