PowerShell JSON Data
JSON is a text format that stores data as named values. It is a plain text way to pass structured data between programs.
Turn an object into one-line JSON
ConvertTo-Json writes the object as text. -Compress keeps it on one line.
$book = [PSCustomObject]@{ Title = "Dune"; Author = "Frank Herbert"; Year = 1965 }
ConvertTo-Json -InputObject $book -CompressTurn JSON text back into an object
ConvertFrom-Json rebuilds the object. A dot then reads each property back.
$json = '{"Title":"Dune","Year":1965}'
$book = $json | ConvertFrom-Json
$book.Title
$book.YearRaise the depth for nested data
The default depth cuts the deepest level off into a short text form. -Depth 3 writes it out in full.
$outer = [PSCustomObject]@{ Name = "Top"; L1 = [PSCustomObject]@{ L2 = [PSCustomObject]@{ L3 = [PSCustomObject]@{ Value = "found" } } } }
ConvertTo-Json -InputObject $outer -Compress -WarningAction SilentlyContinue
ConvertTo-Json -InputObject $outer -Compress -Depth 3Example
$book = [PSCustomObject]@{ Title = "Dune"; Author = "Frank Herbert"; Year = 1965 }
$json = $book | ConvertTo-Json -Compress
$json
$back = $json | ConvertFrom-Json
$back.AuthorKey points
- ConvertTo-Json: Use ConvertTo-Json to turn an object into JSON text.
- Compress: The -Compress switch puts the JSON on one line with no extra spaces.
- ConvertFrom-Json: Use ConvertFrom-Json to turn JSON text back into an object.
- Property order: A PSCustomObject keeps its properties in the order they were written.
- Depth: The -Depth value sets how many levels of nested data are written out in full.
In this example, the object is turned into one-line JSON text and printed. The text is then turned back into an object, and the Author property is read from it.
Note
The default depth is 2, so deeper levels are cut off unless -Depth is raised.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does ConvertTo-Json -Compress do?