0

I need to convert the following Json to CSV format. All the fields in the attrs will become the headers of the CSV. (There are many more columns in attrs - a couple of hundreds). The data and data2 values are joined by data. Relations.

$str = '{
    "data": [
        { "attrs": { "id": "A", "more": "A" }, 
          "relations": [{"id": "r11"}, {"id": "r12"}] },
        { "attrs": { "id": "B", "more": "B" }, 
          "relations": [{"id": "r21"}] }
    ],
    "data2": [
        {"id": "r11", "attrs": { "r": "11"}},
        {"id": "r12", "attrs": { "r": "12"}},
        {"id": "r21", "attrs": { "r": "21"}}
    ]}'
$json = $str | ConvertFrom-Json

The following command

$json.data | select -ExpandProperty attrs | ConvertTo-Csv

got

"id","more"
"A","A"
"B","B"

And

$json.data | 
% { 
    $rs = $_.relations.id; $rs | 
    % { ($json.data2 | ? id -eq $_).attrs | select r } 
} | 
ConvertTo-Csv

got the following values.

"r"
"11"
"12"
"21"

The expected result should be

"id","more","r"
"A","A","11"
"A","A","12"
"B","B","21"
ca9163d9
  • 27,283
  • 64
  • 210
  • 413

0 Answers0