Read JSON: ConvertFrom-Json

ConvertFrom-Json turns JSON text into objects you can use with dot notation:

PowerShell
$json = '{"name":"Emily","roles":["admin","editor"],"address":{"city":"London"}}'
$user = $json | ConvertFrom-Json

$user.name            # Emily
$user.roles[1]        # editor
$user.address.city    # London

The result is a PSCustomObject. Arrays become PowerShell arrays, and nested objects become nested objects.

Read a JSON File

PowerShell
$config = Get-Content .\config.json -Raw -Encoding UTF8 | ConvertFrom-Json
  • -Raw reads the file as one string instead of an array of lines, so ConvertFrom-Json receives the whole document at once.
  • -Encoding UTF8 matters in Windows PowerShell 5.1: it reads UTF-8 files without a BOM as the old ANSI code page. A file containing José came back as José without the option and correctly with it.

Get JSON from an API

PowerShell
$user = Invoke-RestMethod -Uri 'https://api.example.com/users/1'
$user.name

Invoke-RestMethod parses a JSON response for you, so you do not need ConvertFrom-Json. To send JSON, see the PowerShell section of how to send JSON with curl.

Write JSON: ConvertTo-Json

PowerShell
$data = [ordered]@{ name = 'Emily'; roles = @('admin', 'editor') }
$data | ConvertTo-Json -Depth 10

Two habits save a lot of trouble: always pass -Depth, and use [ordered] when the order of keys matters. The next sections show why.

The -Depth Trap

ConvertTo-Json only goes 2 levels deep by default. Anything deeper is replaced by its type name. We converted a three-level hashtable:

PowerShell
@{ a = @{ b = @{ c = @{ d = 1 } } } } | ConvertTo-Json -Compress
Output
{"a":{"b":{"c":"System.Collections.Hashtable"}}}

Windows PowerShell 5.1 did this without any warning, so the broken JSON can end up in a file or an API request unnoticed. The fix is to raise the limit:

PowerShell
$data | ConvertTo-Json -Depth 10

The maximum is 100. PowerShell 7 still uses a default depth of 2 but, according to its documentation, prints a warning when it cuts data off.

Single-Item Arrays Become a Single Value

When you pipe an array into ConvertTo-Json, PowerShell sends its items one by one. With one item, the array disappears:

PowerShell
@(1) | ConvertTo-Json -Compress                 # 1
ConvertTo-Json -InputObject @(1) -Compress      # [1]

If an API expects a list, use -InputObject instead of the pipeline. The same applies to empty arrays: ConvertTo-Json -InputObject @() gives [].

Key Order, Dates and Escaping

InputWindows PowerShell 5.1 outputFix
@{ zeta = 1; alpha = 2; mid = 3 }{"alpha":2,"zeta":1,"mid":3} (order changed)Use [ordered]@{ ... }, which kept zeta, alpha, mid
A [datetime] value"\/Date(1795321800000)\/"Convert it first: $date.ToString('o') gives ISO 8601
"a<b>&'c'""a\u003cb\u003e\u0026\u0027c\u0027"Valid JSON that every parser reads correctly; no fix needed

The 5.1 output is also indented in an unusual way, with wide gaps after colons. It is valid JSON. Use -Compress for one line, or paste it into the JSON Formatter for clean indentation.

Save a JSON File Other Tools Can Read

This is the problem that breaks the most pipelines. In a default Windows PowerShell 5.1 session we saved the same JSON in different ways and checked the first bytes of each file:

CommandFile starts withResult
... | ConvertTo-Json > data.jsonFF FE (UTF-16)Python: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff
... | Set-Content -Encoding utf8 data.jsonEF BB BF (UTF-8 with BOM)Node.js: Unexpected token '' (the invisible BOM)
... | Set-Content data.jsonANSI code pageFine for plain English, but José failed in Python with UnicodeDecodeError

Write UTF-8 without a BOM, which every tool accepts:

Windows PowerShell 5.1
$json = $data | ConvertTo-Json -Depth 10
$utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText("$PWD\data.json", $json, $utf8NoBom)
PowerShell 7+
$data | ConvertTo-Json -Depth 10 | Set-Content data.json   # UTF-8 without BOM by default

WriteAllText needs a full path, which is why the example uses $PWD. The BOM error in Node.js is explained in how to read a JSON file in Node.js.

Invalid JSON and Other Errors

For {"name": "Emily",} (a trailing comma), Windows PowerShell 5.1 reported Invalid JSON primitive: ., which does not say much. Paste the text into the JSON Validator to see the exact line and column.

Be careful the other way too: Windows PowerShell 5.1 accepted {'name': 'Emily'} with single quotes, which is not valid JSON. A file that works in your script can still fail in Python, JavaScript or an API. Validate JSON that other programs will read.

Windows PowerShell 5.1 vs PowerShell 7

Everything above was tested in Windows PowerShell 5.1, the version built into Windows. PowerShell 7 (pwsh) is installed separately and, according to its documentation, changes a few things: dates are written as ISO 8601 strings, files are saved as UTF-8 without a BOM, output is indented normally, a warning appears when -Depth cuts data, and ConvertFrom-Json -AsHashtable returns a hashtable instead of a PSCustomObject. Check your version with $PSVersionTable.PSVersion.

Frequently Asked Questions

How do I read a JSON file in PowerShell?

Use Get-Content .\data.json -Raw -Encoding UTF8 | ConvertFrom-Json. -Raw passes the whole file as one string, and -Encoding UTF8 stops Windows PowerShell 5.1 from misreading non-English characters.

Why does ConvertTo-Json show System.Collections.Hashtable?

ConvertTo-Json only converts 2 levels deep by default and replaces deeper data with its type name. Add -Depth 10 (or higher, up to 100) to convert the whole object.

Why does my one-item array become a single value?

Piping sends array items one by one, so a single item loses its array. Use ConvertTo-Json -InputObject @($item) instead of the pipeline to keep the brackets.

Why can't Python or Node.js read my PowerShell JSON file?

In Windows PowerShell 5.1, > writes UTF-16 and -Encoding utf8 adds a BOM. Save with [System.IO.File]::WriteAllText(path, $json, (New-Object System.Text.UTF8Encoding $false)) to get UTF-8 without a BOM.

Related Tools