arraysjsonpowershell

Powershell Object to json array , mimic a Table/CSV


Given any PS object, that might have different number of properties. I need to create a json array of each property values, where the 1st row, would be the name of each property, and subsequent rows the values for each of them.

I thought I could do it pretty easily, but found out the opposite..

let's say my input object is something like this:

$myObj[0..3]

Date_Time           Total_Time  Sub_Time_1 Sub_Time_2
------------------- ----------- ---------- ----------
28/11/2024 00:02:14       67383      14147      12986
28/11/2024 00:03:19       64223       3741      11610
28/11/2024 00:04:15       55636       3577      12246
28/11/2024 00:04:53       37166       2395       6871
...

I want to convert this to a plain json array of arrays.. like this:

[
  ["Date_Time"           ,"Total_Time", "Sub_Time_1", "Sub_Time_2"],
  ["28/11/2024 00:02:14" , 67383      , 14147       , 12986 ], 
  ["28/11/2024 00:03:19" , 64223      , 3741        , 11610 ],
  ["28/11/2024 00:04:15" , 55636      , 3577        , 12246 ],
  ["28/11/2024 00:04:53" , 37166      , 2395        , 6871  ],
...
]

Tryed ConvertTo-Json, but even using -asArray, it creates an Array of json-objects.
[ {}, {} ,... {} ]

But I need array of arrays , with just the values, except the 1st rows which needs to be the name of each "column"

And it needs to be flexible, as the input object may vary, having different property names.

Note: The extra spaces in the json array, was just for readability...


Solution

  • Use a combination of:

    Piping the result to ConvertTo-Json then yields the desired result.

    # Workaround for Windows PowerShell bug affecting to-JSON
    # serialization of arrays.
    if (-not $IsCoreClr) { Remove-TypeData -ErrorAction Ignore System.Array }
    
    $isHeader = $true
    $myObj |
      ForEach-Object {
        if ($isHeader) { $isHeader = $false; , $_.psobject.Properties.Name } 
        $values = $_.psobject.Properties.Value
        , (
            @($values[0].ToString('dd\/MM\/yyyy HH\:mm\:ss')) + 
            $values[1..($values.Count-1)]
          )
      } |
      ConvertTo-Json
    

    Note: