ConvertTo-Json (Microsoft.PowerShell.Utility) - PowerShell (2024)

  • Reference
Module:
Microsoft.PowerShell.Utility

Converts an object to a JSON-formatted string.

Syntax

ConvertTo-Json [-InputObject] <Object> [-Depth <Int32>] [-Compress] [-EnumsAsStrings] [-AsArray] [-EscapeHandling <StringEscapeHandling>] [<CommonParameters>]

Description

The ConvertTo-Json cmdlet converts any .NET object to a string in JavaScript Object Notation(JSON) format. The properties are converted to field names, the field values are converted toproperty values, and the methods are removed.

Note

As of PowerShell 7.2, Extended Type System properties of DateTime andString objects are no longer serialized and only the simple object isconverted to JSON format

You can then use the ConvertFrom-Json cmdlet to convert a JSON-formatted string to a JSONobject, which is easily managed in PowerShell.

Many web sites use JSON instead of XML to serialize data for communication between servers andweb-based apps.

As of PowerShell 7.1, ConvertTo-Json emits a warning if the depth of the input object exceedsthe depth specified for the command. This prevents unwanted data loss when converting objects.

This cmdlet was introduced in Windows PowerShell 3.0.

Examples

Example 1

(Get-UICulture).Calendar | ConvertTo-Json{ "MinSupportedDateTime": "0001-01-01T00:00:00", "MaxSupportedDateTime": "9999-12-31T23:59:59.9999999", "AlgorithmType": 1, "CalendarType": 1, "Eras": [ 1 ], "TwoDigitYearMax": 2029, "IsReadOnly": true}

This command uses the ConvertTo-Json cmdlet to convert a GregorianCalendar object to aJSON-formatted string.

Example 2

Get-Date | ConvertTo-Json; Get-Date | ConvertTo-Json -AsArray"2021-08-05T16:13:05.6394416-07:00"[ "2021-08-05T16:13:05.6421709-07:00"]

This example shows the output from ConvertTo-Json cmdlet with and without the AsArray switchparameter. You can see the second portion of the output is wrapped in array brackets.

Example 3

@{Account="User01";Domain="Domain01";Admin="True"} | ConvertTo-Json -Compress{"Domain":"Domain01","Account":"User01","Admin":"True"}

This command shows the effect of using the Compress parameter of ConvertTo-Json. Thecompression affects only the appearance of the string, not its validity.

Example 4

Get-Date | Select-Object -Property * | ConvertTo-Json{ "DisplayHint": 2, "DateTime": "October 12, 2018 10:55:32 PM", "Date": "2018-10-12T00:00:00-05:00", "Day": 12, "DayOfWeek": 5, "DayOfYear": 285, "Hour": 22, "Kind": 2, "Millisecond": 639, "Minute": 55, "Month": 10, "Second": 32, "Ticks": 636749817326397744, "TimeOfDay": { "Ticks": 825326397744, "Days": 0, "Hours": 22, "Milliseconds": 639, "Minutes": 55, "Seconds": 32, "TotalDays": 0.95523888627777775, "TotalHours": 22.925733270666665, "TotalMilliseconds": 82532639.774400011, "TotalMinutes": 1375.54399624, "TotalSeconds": 82532.6397744 }, "Year": 2018}

This example uses the ConvertTo-Json cmdlet to convert a System.DateTime object from theGet-Date cmdlet to a JSON-formatted string. The command uses the Select-Object cmdlet to get all(*) of the properties of the DateTime object. The output shows the JSON string thatConvertTo-Json returned.

Example 5

Get-Date | Select-Object -Property * | ConvertTo-Json | ConvertFrom-JsonDisplayHint : 2DateTime : October 12, 2018 10:55:52 PMDate : 2018-10-12 12:00:00 AMDay : 12DayOfWeek : 5DayOfYear : 285Hour : 22Kind : 2Millisecond : 768Minute : 55Month : 10Second : 52Ticks : 636749817527683372TimeOfDay : @{Ticks=825527683372; Days=0; Hours=22; Milliseconds=768; Minutes=55; Seconds=52; TotalDays=0.95547185575463; TotalHours=22.9313245381111; TotalMilliseconds=82552768.3372; TotalMinutes=1375.87947228667; TotalSeconds=82552.7683372}Year : 2018

This example shows how to use the ConvertTo-Json and ConvertFrom-Json cmdlets to convert anobject to a JSON string and a JSON object.

Parameters

-AsArray

Outputs the object in array brackets, even if the input is a single object.

Type:SwitchParameter
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Compress

Omits white space and indented formatting in the output string.

Type:SwitchParameter
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Depth

Specifies how many levels of contained objects are included in the JSON representation. The valuecan be any number from 0 to 100. The default value is 2. ConvertTo-Json emits awarning if the number of levels in an input object exceeds this number.

Type:Int32
Position:Named
Default value:2
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-EnumsAsStrings

Provides an alternative serialization option that converts all enumerations to their string representation.

Type:SwitchParameter
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-EscapeHandling

Controls how certain characters are escaped in the resulting JSON output. By default, only controlcharacters (like newline) are escaped.

Acceptable values are:

  • Default - Only control characters are escaped.
  • EscapeNonAscii - All non-ASCII and control characters are escaped.
  • EscapeHtml - HTML (<, >, &, ', ") and control characters are escaped.

This parameter was introduced in PowerShell 6.2.

Type:Newtonsoft.Json.StringEscapeHandling
Position:Named
Default value:Default
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-InputObject

Specifies the objects to convert to JSON format. Enter a variable that contains the objects, or typea command or expression that gets the objects. You can also pipe an object to ConvertTo-Json.

The InputObject parameter is required, but its value can be null ($null) or an empty string.When the input object is $null, ConvertTo-Json returns the JSON representation of null. Whenthe input object is an empty string, ConvertTo-Json returns the JSON representation of an emptystring.

Type:Object
Position:0
Default value:None
Required:True
Accept pipeline input:True
Accept wildcard characters:False

Inputs

Object

You can pipe any object to this cmdlet.

Outputs

String

This cmdlet returns a string representing the input object converted to a JSON string.

Notes

The ConvertTo-Json cmdlet is implemented usingNewtonsoft Json.NET.

  • An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET
  • ConvertFrom-Json
  • Get-Content
  • Get-UICulture
  • Invoke-WebRequest
  • Invoke-RestMethod
  • NewtonSoft.Json.StringEscapeHandling
ConvertTo-Json (Microsoft.PowerShell.Utility) - PowerShell (2024)

FAQs

How to use ConvertTo.JSON in PowerShell? ›

-InputObject

Specifies the objects to convert to JSON format. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe an object to ConvertTo-Json . The InputObject parameter is required, but its value can be null ( $null ) or an empty string.

How to format JSON output in PowerShell? ›

PowerShell uses the two cmdlets ConvertTo-JSON and ConvertFrom-JSON to work with JSON files. The ConvertTo-JSON cmdlet converts any possible output to the JSON format and the ConvertFrom-JSON cmdlet converts the JSON input to the custom Object or the hashtable format.

How to convert JSON to string in PowerShell? ›

This command uses the Invoke-WebRequest cmdlet to get JSON strings from a web service and then it uses the ConvertFrom-Json cmdlet to convert JSON content to objects that can be managed in Windows PowerShell. You can also use the Invoke-RestMethod cmdlet, which automatically converts JSON content to objects.

How to get response in JSON format? ›

Response: json() method

The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

How to convert JSON response to object? ›

To convert a JSON string to a JavaScript object, you can use the JSON. parse() method. This method takes a JSON string as input and returns a JavaScript object. In the example above, we have a JSON string jsonString that represents an object with properties such as name , age , and city .

How to convert the JSON format? ›

Stringify a JavaScript Object

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

How to extract data from JSON output? ›

To extract JSON data from a column and put it in separate columns:
  1. Go to the column in the workbook. ...
  2. Use the column's menu to select Extract columns. ...
  3. In the modal, select the fields you want to pull out into their own columns.
  4. Click Confirm. ...
  5. Use the new columns in your explorations and analysis.

How to convert command output to JSON? ›

To convert output to json, use the --tojson (or -j ) flag. This is supported by all commands. You can change the json output format by using the pretty print or indent flags.

Can PowerShell read a JSON file? ›

To read a JSON file into an array in PowerShell, use the Get-Content cmdlet to retrieve the file content and pipe it to the ConvertFrom-Json cmdlet. For example, $array = Get-Content -Path 'file. json' | ConvertFrom-Json will parse the JSON file into a PowerShell array if the JSON is an array format.

How to get a value from a JSON response? ›

Getting a specific property from a JSON response object

The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object. Smart technical documentation with easy content reuse.

How to decode JSON response? ›

The json_decode() function is used to decode or convert a JSON object to a PHP object.

How to convert string into JSON in PowerShell? ›

To convert a string to JSON in PowerShell, the most common and straightforward method is using the ConvertTo-Json cmdlet. This cmdlet takes PowerShell objects as input and converts them into a JSON-formatted string.

How to convert a JSON string into JSON? ›

Conversion of JSON String into JSON Object

// creating object of Gson Gson gson = new Gson(); // calling method fromJson and passing JSON string into object // The first parameter is JSON string // The second parameter is the Java class to parse the JSON into an instance of. object = gson. fromJson(jsonString,GFG.

How to call a JSON file in PowerShell? ›

To read a JSON file into an array in PowerShell, use the Get-Content cmdlet to retrieve the file content and pipe it to the ConvertFrom-Json cmdlet. For example, $array = Get-Content -Path 'file. json' | ConvertFrom-Json will parse the JSON file into a PowerShell array if the JSON is an array format.

How to convert JSON output to CSV in PowerShell? ›

To convert the JSON file to the CSV file using PowerShell, we need to use the ConvertTo-CSV command as a pipeline. For example, we have a JSON file called PatchingServer. JSON stored at C:\temp and its content is as below.

How to update JSON in PowerShell? ›

How to Edit a JSON File in PowerShell (With Example)
  1. First, retrieve the JSON file named my_teams. json.
  2. Next, for each value in the Location field of the file that is equal to 'Dallas', update the corresponding value in the Name field to be equal to 'Mavs'
  3. Lastly, output these changes to a new JSON file named new_teams.
Jun 14, 2024

How do I run an Exchange script in PowerShell? ›

Connect to a remote Exchange server
  1. On your local computer, open Windows PowerShell, and run the following command: PowerShell Copy. $UserCredential = Get-Credential. ...
  2. Run the following command: PowerShell Copy. Import-PSSession $Session -DisableNameChecking.
Sep 7, 2023

Top Articles
Overbought vs. Oversold Signals: How to Identify Them | Binance Blog
Net worth
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Lidia Grady

Last Updated:

Views: 6004

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.