To achieve the desired output, you need to loop through the Data array in your JSON, calculate the total Cost for each Header row, and then iterate through the Items to create Item rows. Below is the corrected PowerShell script to process your JSON:
PowerShell Script
# Load the JSON file
$json = Get-Content -Path 'response.json' | ConvertFrom-Json
# Iterate through each "Data" entry
foreach ($entry in $json.Data) {
# Calculate the total cost for the header row
$totalCost = ($entry.Items | Measure-Object -Property Amount -Sum).Sum
# Print the Header row
Write-Output "row ID CODE Cost"
Write-Output "Header $($entry.ID) $($entry.Code) $totalCost"
# Iterate through each Item and print its details
$itemNumber = 1
foreach ($item in $entry.Items) {
Write-Output "Item $itemNumber $($entry.ID) $($entry.Code) $($item.Amount)"
$itemNumber++
}
# Add a blank line between entries for clarity
Write-Output ""
}
Explanation of the Script
Load JSON:
Use Get-Content and ConvertFrom-Json to load and parse the JSON file into a PowerShell object.
Iterate through Data:
Loop through each entry in the Data array using foreach.
Calculate Total Cost:
Use Measure-Object with the -Property Amount -Sum to calculate the total cost of all Items for each entry.
Print Header Row:
Use Write-Output to display the Header row with the total cost.
Iterate through Items:
Loop through each Item in the Items array and print the details, incrementing the Item number for each.
Formatting:
Use blank lines for readability between sections.
Output
For the provided JSON, the script will produce the following output: