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

  • Reference
Module:
Microsoft.PowerShell.Utility

Converts a JSON-formatted string to a custom object or a hash table.

Syntax

ConvertFrom-Json [-InputObject] <String> [-AsHashtable] [-Depth <Int32>] [-NoEnumerate] [<CommonParameters>]

Description

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to acustom PSObject or Hashtable object that has a property for each field in the JSON string.JSON is commonly used by web sites to provide a textual representation of objects. The cmdlet addsthe properties to the new object as it processes each line of the JSON string.

The JSON standard allows duplicate key names, which are prohibited in PSObject and Hashtabletypes. For example, if the JSON string contains duplicate keys, only the last key is used by thiscmdlet. See other examples below.

To generate a JSON string from any object, use the ConvertTo-Json cmdlet.

This cmdlet was introduced in PowerShell 3.0.

Note

Beginning with PowerShell 6, the cmdlet supports JSON with comments. JSON comments start with twoforward slashes (//) characters. JSON comments aren't captured in the objects output by thecmdlet. Prior to PowerShell 6, ConvertFrom-Json would return an error when it encountered a JSONcomment.

Examples

Example 1: Convert a DateTime object to a JSON object

This command uses the ConvertTo-Json and ConvertFrom-Json cmdlets to convert a DateTimeobject from the Get-Date cmdlet to a JSON object then to a PSCustomObject.

Get-Date | Select-Object -Property * | ConvertTo-Json | ConvertFrom-JsonDisplayHint : 2DateTime : Friday, January 13, 2012 8:06:31 PMDate : 1/13/2012 8:00:00 AMDay : 13DayOfWeek : 5DayOfYear : 13Hour : 20Kind : 2Millisecond : 400Minute : 6Month : 1Second : 31Ticks : 634620819914009002TimeOfDay : @{Ticks=723914009002; Days=0; Hours=20; Milliseconds=400; Minutes=6; Seconds=31; TotalDays=0.83786343634490734; TotalHours=20.108722472277776; TotalMilliseconds=72391400.900200009; TotalMinutes=1206.5233483366667;TotalSeconds=72391.4009002}Year : 2012

The example uses the Select-Object cmdlet to get all of the properties of the DateTimeobject. It uses the ConvertTo-Json cmdlet to convert the DateTime object to a stringformatted as a JSON object and the ConvertFrom-Json cmdlet to convert the JSON-formatted stringto a PSCustomObject object.

Example 2: Get JSON strings from a web service and convert them to PowerShell objects

This command uses the Invoke-WebRequest cmdlet to get JSON strings from a web serviceand then it uses the ConvertFrom-Json cmdlet to convert JSON content to objectsthat can be managed in PowerShell.

# Ensures that Invoke-WebRequest uses TLS 1.2[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12$j = Invoke-WebRequest 'https://api.github.com/repos/PowerShell/PowerShell/issues' | ConvertFrom-Json

You can also use the Invoke-RestMethod cmdlet, which automatically converts JSON content toobjects.

Example 3: Convert a JSON string to a custom object

This example shows how to use the ConvertFrom-Json cmdlet to convert a JSON file to a PowerShellcustom object.

Get-Content -Raw JsonFile.JSON | ConvertFrom-Json

The command uses Get-Content cmdlet to get the strings in a JSON file. The Raw parameterreturns the whole file as a single JSON object. Then it uses the pipeline operator to send thedelimited string to the ConvertFrom-Json cmdlet, which converts it to a custom object.

Example 4: Convert a JSON string to a hash table

This command shows an example where the -AsHashtable switch can overcome limitations of thecommand.

'{ "key":"value1", "Key":"value2" }' | ConvertFrom-Json -AsHashtable

The JSON string contains two key value pairs with keys that differ only in casing. Without theswitch, the command would have thrown an error.

Example 5: Round-trip a single element array

This command shows an example where the -NoEnumerate switch is used to round-trip a single elementJSON array.

Write-Output "With -NoEnumerate: $('[1]' | ConvertFrom-Json -NoEnumerate | ConvertTo-Json -Compress)"Write-Output "Without -NoEnumerate: $('[1]' | ConvertFrom-Json | ConvertTo-Json -Compress)"With -NoEnumerate: [1]Without -NoEnumerate: 1

The JSON string contains an array with a single element. Without the switch, converting the JSON toa PSObject and then converting it back with the ConvertTo-Json command results in a singleinteger.

Parameters

-AsHashtable

Converts the JSON to a hash table object. This switch was introduced in PowerShell 6.0. Startingwith PowerShell 7.3, the object is an OrderedHashtable and preserves the ordering of the keysfrom the JSON. In prior versions, the object is a Hashtable.

There are several scenarios where it can overcome some limitations of the ConvertFrom-Json cmdlet.

  • Without this switch, when two or more keys in a JSON object are case-insensitively identical, theyare treated as identical keys. In that case, only the last of those case-insensitively identicalkeys is included in the converted object.
  • Without this switch, the cmdlet throws an error whenever the JSON contains a key that's an emptystring. PSCustomObject can't have property names that are empty strings. For example, this canoccur in project.lock.json files.
  • Hash tables can be processed faster for certain data structures.
Type:SwitchParameter
Position:Named
Default value:False
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-Depth

Gets or sets the maximum depth the JSON input is allowed to have. The default is 1024.

This parameter was introduced in PowerShell 6.2.

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

-InputObject

Specifies the JSON strings to convert to JSON objects. Enter a variable that contains the string,or type a command or expression that gets the string. You can also pipe a string toConvertFrom-Json.

The InputObject parameter is required, but its value can be an empty string. When the inputobject is an empty string, ConvertFrom-Json doesn't generate any output. The InputObjectvalue can't be $null.

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

-NoEnumerate

Specifies that output isn't enumerated.

Setting this parameter causes arrays to be sent as a single object instead of sending every elementseparately. This guarantees that JSON can be round-tripped via ConvertTo-Json.

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

Inputs

String

You can pipe a JSON string to ConvertFrom-Json.

Outputs

PSCustomObject

OrderedHashtable

Notes

This cmdlet is implemented using Newtonsoft Json.NET.

Beginning in PowerShell 6, ConvertTo-Json attempts to convert strings formatted as timestamps toDateTime values. The converted value is a [datetime] instance with a Kind property set asfollows:

  • Unspecified, if there is no time zone information in the input string.
  • Utc, if the time zone information is a trailing Z.
  • Local, if the time zone information is given as a trailing UTC offset like +02:00. Theoffset is properly converted to the caller's configured time zone. The default output formattingdoesn't indicate the original time zone offset.

The PSObject type maintains the order of the properties as presented in the JSON string.Beginning with PowerShell 7.3, The AsHashtable parameter creates an OrderedHashtable. Thekey-value pairs are added in the order presented in the JSON string. The OrderedHashtablepreserves that order.

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

FAQs

ConvertFrom-Json (Microsoft.PowerShell.Utility) - PowerShell? ›

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSObject or Hashtable object that has a property for each field in the JSON string. JSON is commonly used by web sites to provide a textual representation of objects.

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 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-content from 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 format JSON with 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 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 change the JSON to a JSON object? ›

There are several methods that can be used to change JSON String into an Object.
  1. Using JSON.parse()
  2. Using String.prototype.replace() with a regex pattern.
  3. Using Function() constructor.
  4. Using JSON.parse() with a try-catch block.
Sep 8, 2023

What is the best way to convert JSON to string? ›

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr);

How to convert string in JSON format? ›

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval(), which accepts the JavaScript expression that you will learn about in this guide.

How to extract content from JSON? ›

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 do I parse a JSON file? ›

Example - Parsing JSON

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How to get the content of a JSON file? ›

Reading a JSON file using JavaScript allows you to access and manipulate data stored in JSON format. This can be done in the browser with fetch() or in Node. js using fs. readFile() or require().

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 convert JSON to readable format? ›

You can convert JSON to TXT with MConverter in three easy steps:
  1. Choose JSON files from your device. At the top of this page, drag and drop your JSONs. ...
  2. Click or tap on TXT from the list of target formats. ...
  3. Download your TXT files, after MConverter has finished processing them.

How to convert string to 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 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

How to convert JSON to hash table in PowerShell? ›

We can use the pipeline command ConvertFrom−JSON to convert the JSON file to the custom table format and with the −AsHashtable parameter to convert the custom object to the hashtable.

Top Articles
What sweeter revenge than forgiveness?
Chenoa Fund Lender FAQ | CBC Mortgage Agency
Riverrun Rv Park Middletown Photos
Instructional Resources
25X11X10 Atv Tires Tractor Supply
Collision Masters Fairbanks
Carter Joseph Hopf
Delectable Birthday Dyes
Shariraye Update
123Moviescloud
4302024447
Babyrainbow Private
Craigslist Pikeville Tn
Minecraft Jar Google Drive
Leader Times Obituaries Liberal Ks
Katherine Croan Ewald
Directions To Advance Auto
Mikayla Campinos Laek: The Rising Star Of Social Media
Site : Storagealamogordo.com Easy Call
Long Island Jobs Craigslist
Dallas Mavericks 110-120 Golden State Warriors: Thompson leads Warriors to Finals, summary score, stats, highlights | Game 5 Western Conference Finals
Pasco Telestaff
The EyeDoctors Optometrists, 1835 NW Topeka Blvd, Topeka, KS 66608, US - MapQuest
Delta Township Bsa
Usa Massage Reviews
Lacey Costco Gas Price
Wheeling Matinee Results
Craig Woolard Net Worth
Obsidian Guard's Skullsplitter
6465319333
Baldur's Gate 3 Dislocated Shoulder
RFK Jr., in Glendale, says he's under investigation for 'collecting a whale specimen'
Pitco Foods San Leandro
Dr. John Mathews Jr., MD – Fairfax, VA | Internal Medicine on Doximity
Regis Sectional Havertys
Google Chrome-webbrowser
Craigslist Gigs Wichita Ks
Second Chance Apartments, 2nd Chance Apartments Locators for Bad Credit
No Boundaries Pants For Men
18006548818
Avatar: The Way Of Water Showtimes Near Jasper 8 Theatres
Squalicum Family Medicine
Tommy Bahama Restaurant Bar & Store The Woodlands Menu
Vci Classified Paducah
Wisconsin Volleyball titt*es
855-539-4712
Bismarck Mandan Mugshots
Pronósticos Gulfstream Park Nicoletti
Fresno Craglist
Sleep Outfitters Springhurst
Lsreg Att
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 5988

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.