0

I have the following object which needs to be converted to CSV file. The CSV file columns will contain all data.attrs and data2.attrs. data and data2 are referenced 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": { "x": "11", "y": "1"}},
        {"id": "r12", "attrs": { "x": "12", "y": "2"}},
        {"id": "r21", "attrs": { "x": "21", "y": "1"}}
    ]}'
$json = $str | ConvertFrom-Json

The following code got all the attrs in data2 for each row in data.

$json.data | 
% { 
    $_.relations.id | 
    % { 
        $json.data2 | ? id -eq $_ | select -ExpandProperty attrs # need to add data.attrs
    } 
} | 
ConvertTo-Csv

Output

"x","y"
"11","1"
"12","2"
"21","1"

How to add the columns from data in the list? There are many columns/fields in data.attr.

Expected

"id","more",....,"x","y"
"A","A",....,"11","1"
"A","A",....,"12","2"
"B","B",....,"21","1"
ca9163d9
  • 27,283
  • 64
  • 210
  • 413

1 Answers1

0

Your data and data2 properties have different structures. To align (and flatten) the data properties and the data2 properties, you might do this:

$Data = $json.data.foreach{
    foreach ($relation in $_.relations) {
        [pscustomobject]@{
            relation = $relation.id
            id = $_.attrs.id
            more = $_.attrs.more
        }
    }
}
$Data

relation id more
-------- -- ----
r11      A  A
r12      A  A
r21      B  B  



$data2 = $json.data2.foreach{
    [pscustomobject]@{
        id = $_.id
        x = $_.attrs.x
        y = $_.attrs.y
    }
}
$Data2

id  x  y
--  -  -
r11 11 1
r12 12 2
r21 21 1

To zip the object lists, you might use this Join-Object script/Join-Object Module (see also: Is there a PowerShell equivalent of paste):

$data |Join $data2 -Name '',*2 |Format-Table

relation id id2 more x  y
-------- -- --- ---- -  -
r11      A  r11 A    11 1
r12      A  r12 A    12 2
r21      B  r21 B    21 1

For joining the objects, see your next question: Join two objects - cannot add a member with the name "x" because a member with that name already exists?.

iRon
  • 20,463
  • 10
  • 53
  • 79