jsonpowershellcsvdata-conversion

Convert a JSON representation of CSV data to actual CSV data


This self-answered question is about transforming a JSON representation of CSV data into actual CSV data.

The following JSON contains separate properties that describe the headers (column names) (columns) and arrays of corresponding row values (rows), respectively:

{
  "columns": [
      {
          "name": "ColumnName1",
          "type": "Number"
      },
      {
          "name": "ColumnName2",
          "type": "String"
      },
      {
          "name": "ColumnName3",
          "type": "String"
      }
  ],
  "rows":    [
      [
          11111,
          "ResourceType1",
          "String1"
      ],
      [
          22222,
          "ResourceType2",
          "String2"
      ],
      [
          33333,
          "ResourceType3",
          "String3"
      ]
  ]
}

How can I convert this JSON input to the CSV data it represents?


Solution

  • Caveat:


    Assume that the JSON in the question is saved in file file.json, which can be parsed into a ([pscustomobject]) object graph with ConvertFrom-Json, via reading the file as text with Get-Content:

    # Convert the JSON text into a [pscustomobject] object graph.
    $fromJson = Get-Content -Raw file.json | ConvertFrom-Json
    
    # Process the array of column names and the arrays of row values by
    # enclosing the array elements in "..." and joining them with ","
    (, $fromJson.Columns.Name + $fromJson.Rows).ForEach({
      $_.ForEach({ '"{0}"' -f ($_ -replace '"', '""') }) -join ','
    })
    

    Note:

    The above outputs:

    "ColumnName1","ColumnName2","ColumnName3"
    "11111","ResourceType1","String1"
    "22222","ResourceType2","String2"
    "33333","ResourceType3","String3"