Powershell

How to Use the ConvertTo-Json (Microsoft.PowerShell.Utility) Cmdlet in PowerShell?

The PowerShell cmdlet “ConvertTo-Json” is utilized to convert .NET objects to a JSON-formatted string. It is going to be plain text after the conversion. Following the conversion, properties are converted to field names, and the field values are converted to property values. However, methods get removed after the conversion. The stated cmdlet was first introduced in PowerShell 3.0.

In this particular tutorial, the PowerShell “ConvertTo-Json” cmdlet will be explained.

How to Use the ConvertTo-Json (Microsoft.PowerShell.Utility) Cmdlet in PowerShell?

The cmdlet “ConvertTo-Json” uses some of the optional parameters, including “-AsArray”, “-Depth”, “-Compress”, “-InputObject”, “-EscapeHandling”, or “-EnumAsStrings”. Using these parameters alongside the stated cmdlet will produce customized results.

Let’s explore some of the examples related to the “ConvertTo-Json” cmdlet in PowerShell.

Example 1: Get the UI Culture User Interface and Convert it to JSON Format

To convert the date into JSON format, execute the following command:

(Get-UICulture).Calendar | ConvertTo-Json

According to the above-stated code:

  • First, concatenate the “Calendar” with the “Get-UICulture” cmdlet.
  • Then, add the “|” pipeline and specify the “ConvertTo-Json” command:

Example 2: Get the Date and Convert it into an Array

To convert a date to an array, initially, specify the “Get-Date” cmdlet and the “|” pipeline to transfer the output to the next cmdlet. Then, provide the “ConvertTo-Json” cmdlet alongside the “-AsArray” parameter:

Get-Date | ConvertTo-Json -AsArray

Example 3: Get the Date, Select its Object, and Convert it to JSON Format

Run the given cmdlet to convert the selected objects to JSON format:

Get-Date | Select-Object -Property * | ConvertTo-Json

In the above-provided code:

  • Write the “Get-Date” cmdlet and add the “|” pipeline.
  • Then, write the “Select-Object” to select the objects with the “-Property” parameter and the wildcard “*”.
  • After that, add the “|” pipeline and specify the “ConvertTo-Json” to convert to the JSON format:

This article provided details about the “ConvertTo-Json” cmdlet in PowerShell.

Conclusion

The “ConvertTo-Json” cmdlet converts the .NET string objects to JSON “JavaScript Object Notation” format. The converted output will be in plain text JSON format. Moreover, it uses optional parameters to get the customized output. The tutorial explained the “ConvertTo-Json” cmdlet with the help of various scenario-based examples.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.