TExcelTAD
Home › PowerShell › PowerShell CSV & JSON

PowerShell CSV & JSON

Real automation exchanges data with other tools: spreadsheets export CSV, web APIs speak JSON. PowerShell converts both formats to and from objects in one command, so the rest of your pipeline doesn't care where the data came from.

Format Text ↔ objects Files
CSV ConvertFrom-Csv, ConvertTo-Csv Import-Csv, Export-Csv
JSON ConvertFrom-Json, ConvertTo-Json Get-Content -Raw | ConvertFrom-Json, … | Set-Content

Reading CSV

Each CSV row becomes an object, with one property per column (taken from the header line):

powershell · try it yourself
$csv = @'
Name,Department,Salary
Ada,Research,8200
Linus,Engineering,7600
Grace,Engineering,9100
Alan,Research,7900
'@

$staff = $csv | ConvertFrom-Csv
$staff.Count
$staff[0].Name
$staff | Where-Object Department -eq 'Engineering' | ForEach-Object Name
4
Ada
Linus
Grace

CSV values are strings

CSV has no types, so every value is a string. Convert numbers before doing maths or numeric sorting:

powershell · try it yourself
$staff = @'
Name,Salary
Ada,8200
Linus,950
Grace,10100
'@ | ConvertFrom-Csv

$staff[0].Salary.GetType().Name
($staff | Sort-Object Salary).Name -join ', '                  # text order: wrong
($staff | Sort-Object { [int]$_.Salary }).Name -join ', '      # numeric: right
($staff | Measure-Object Salary -Sum).Sum                       # Measure converts for you
String
Grace, Ada, Linus
Linus, Ada, Grace
19250

Writing CSV

Export-Csv writes objects to a file; ConvertTo-Csv returns the lines as strings. PowerShell 7 omits the old #TYPE header line and quotes every value by default; -UseQuotes AsNeeded quotes only when necessary:

powershell · try it yourself
$report = @(
    [pscustomobject]@{ Server = 'web01'; Cpu = 37; Note = 'ok' }
    [pscustomobject]@{ Server = 'db01';  Cpu = 91; Note = 'high, check queries' }
)

$report | ConvertTo-Csv
'---'
$report | ConvertTo-Csv -UseQuotes AsNeeded
'---'
$report | Export-Csv ./report.csv
(Import-Csv ./report.csv | Where-Object { [int]$_.Cpu -gt 80 }).Server
"Server","Cpu","Note"
"web01","37","ok"
"db01","91","high, check queries"
---
Server,Cpu,Note
web01,37,ok
db01,91,"high, check queries"
---
db01

Other useful parameters: -Delimiter ';' (common in European Excel exports), -Append, and -Header on import when the file has no header line.

Reading JSON

ConvertFrom-Json turns JSON text into objects. Nested objects and arrays become nested objects and arrays, and JSON numbers and Booleans keep their types:

powershell · try it yourself
$json = @'
{
  "name": "inventory-api",
  "version": "2.3.1",
  "port": 8080,
  "debug": false,
  "databases": [
    { "name": "main",    "host": "db01" },
    { "name": "reports", "host": "db02" }
  ]
}
'@

$config = $json | ConvertFrom-Json
$config.name
$config.port + 1
$config.debug.GetType().Name
$config.databases.Count
$config.databases[1].host
$config.databases.name -join ', '
inventory-api
8081
Boolean
2
db02
main, reports

-AsHashtable returns hashtables instead of objects, which is handy when keys aren't valid property names or you want to add keys later. To read a JSON file use Get-Content ./config.json -Raw | ConvertFrom-Json; the -Raw matters, because the parser needs the whole text at once.

Writing JSON and the -Depth trap

ConvertTo-Json serialises objects and hashtables. By default it only goes 2 levels deep; deeper levels are cut off and turned into strings with a warning. Set -Depth when your data is nested:

powershell · try it yourself
$deploy = [ordered]@{
    app     = 'shop'
    targets = @(
        [ordered]@{ env = 'test'; servers = @('t1', 't2'); limits = @{ cpu = 2 } }
    )
}

$deploy | ConvertTo-Json -Compress
'---'
$deploy | ConvertTo-Json -Depth 5 -Compress
'---'
$deploy | ConvertTo-Json -Depth 5
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{"app":"shop","targets":[{"env":"test","servers":"t1 t2","limits":"System.Collections.Hashtable"}]}
---
{"app":"shop","targets":[{"env":"test","servers":["t1","t2"],"limits":{"cpu":2}}]}
---
{
  "app": "shop",
  "targets": [
    {
      "env": "test",
      "servers": [
        "t1",
        "t2"
      ],
      "limits": {
        "cpu": 2
      }
    }
  ]
}

-Compress writes everything on one line, good for APIs and logs; without it you get indented, human-friendly JSON.

Round trip: CSV in, JSON out

Because both converters work with objects, translating between formats is a pipeline:

powershell · try it yourself
@'
sku,product,qty
A-1,Widget,4
B-7,Gadget,0
C-3,Doohickey,12
'@ | ConvertFrom-Csv |
    Where-Object { [int]$_.qty -gt 0 } |
    Select-Object sku, @{ N = 'qty'; E = { [int]$_.qty } } |
    ConvertTo-Json -Compress
[{"sku":"A-1","qty":4},{"sku":"C-3","qty":12}]

Note how the calculated property converts qty to a number, so the JSON contains 4 instead of "4".

Tip: For REST APIs, Invoke-RestMethod does the JSON conversion for you: it sends -Body ($data | ConvertTo-Json) and returns already-parsed objects. It needs network access, so it's not run here.

Test yourself

What type are the values of objects produced by Import-Csv?

  1. Detected automatically (int, date, ...)
  2. Always strings
  3. Always numbers
  4. Hashtables

Your nested JSON output shows System.Collections.Hashtable instead of data. What fixes it?

  1. -Compress
  2. -Depth with a larger value
  3. -AsHashtable
  4. Out-String

Why use Get-Content file.json -Raw before ConvertFrom-Json?

  1. It is faster to type
  2. It returns the whole file as one string instead of an array of lines
  3. It removes comments
  4. It validates the JSON