In powershell I'm trying to convert CSV file to JSON with nested array of Size object by grouping products. In code below $ProductLines come from CSV file as powershell object.
$UniqueProducts = $ProductLines | Group-Object -Property 'ProductNumber' | ForEach-Object {
$SizeObj = ($_.Group | Select-Object -Property `
@{name="SizeCode"; Expression = {$_.Sizes}}, @{name="UPC"; Expression = {$_.UPCNo}} `
)
#$SizeObj | ConvertTo-Json -depth 10 | Out-File "C:\POWERSHELL\Sizes.txt"
$_.Group | Select-Object -Property ProductNumber, ProductName, `
@{name="Sizes"; Expression = {$SizeObj}} -Unique
}
$UniqueProducts | ConvertTo-Json -depth 10 | Out-File "C:\POWERSHELL\UniqueProducts.txt"
The above code produces JSON file with below structure with additional layer value: and Count:
[
{
"ProductNumber": "EBAGS101-00008",
"ProductName": "EBAGS101",
"Sizes": {
"value": [
{
"SizeCode": "XS",
"UPC": "201112291509"
},
{
"SizeCode": "S",
"UPC": "201112291510"
}
],
"Count": 2
}
},
{
"ProductNumber": "EBAGS101-001",
"ProductName": "EBAGS101",
"Sizes": {
"value": [
{
"SizeCode": "XS",
"UPC": ""
},
{
"SizeCode": "S",
"UPC": "098617106215"
}
],
"Count": 2
}
}
]
How can I remove value and Count layer from my result. When I output just $SizeObj it doesn't have value and Count, I'm not sure how value and Count ends up in $UniquProducts. In my end result I'm trying to create SizeObj in the below format (without value and Count):
"Sizes": [
{
"SizeCode": "XS",
"UPC": "201112291509"
},
{
"SizeCode": "S",
"UPC": "201112291510"
}
]
UPDATE: using answer provided by @RoadRunner here is the modified solution with csv source; where $ProductLines is converted Powershell object from csv file:
$Products = New-Object -TypeName System.Collections.ArrayList
$ProductLines | Group-Object -Property 'ProductNumber' | ForEach-Object {
$SizeRanges = New-Object -TypeName System.Collections.ArrayList
foreach ($object in $_.Group) {
$SizeVal = [PSCustomObject]@($object | Select-Object -Property `
@{name="SizeCode"; Expression = {$_.Sizes}}, `
@{name="UPC"; Expression = {$_.UPCNo}}`
)
$SizeRanges.AddRange($SizeVal)|Out-Null
}
$grp = $_.Group[0];
$product = [PSCustomObject]@{
ProductNumber = $grp.ProductNumber
ProductName = $grp.ProductName
Sizes = $SizeRanges
}
$products.Add($product)|Out-Null
} | ConvertTo-Json -Depth 3 | Out-File -FilePath output.json