Home > database >  Convert a list to CSV with customized logic for each row?
Convert a list to CSV with customized logic for each row?

Time:11-14

I have the following code to get the list.

$str = '[
    {"attrs": { "id": "A", "repeat": 2}},
    {"attrs": { "id": "B", "repeat": 3}}
    ]'
$json = $str | ConvertFrom-Json

I want to convert it to the CSV. The row should be repeated by the value of the repeat property.

id,repeat
A,2
A,2
B,3
B,3
B,3

The following code

$json | % { $_.attrs | ConvertTo-Csv -NoTypeInformation -UseQuotes AsNeeded | select -Skip 1 }

generates the following result. How to implement the log to repeat the rows? (The actual logic is more complex and the language feature such as generator can be helpful, however, Powershell seems to not have it.)

A,2
B,3

CodePudding user response:

You can use the range operator .. and an inner loop:

$json.attrs | ForEach-Object {
    foreach($i in 1..$_.repeat) { $_ }
} | Export-Csv path\to\csv.csv -NoTypeInformation

If you want to have the file with no headers, then ConvertTo-Csv can also be outside the loop:

$json.attrs | ForEach-Object {
    foreach($i in 1..$_.repeat) { $_ }
} | ConvertTo-Csv -UseQuotes AsNeeded | Select-Object -Skip 1
  • Related