Serialization and deserialization of PowerShell objects


PowerShell / Operation and Maintenance


Serialization and deserialization of PowerShell objects

Author: Li Juncai (jcLee95): https://blog.csdn.net/qq_28550263
Email:[email protected]
This article address: https://blog.csdn.net/qq_28550263/article/details/132871258


Directory

  • 1. Overview
  • 2. Serialization: Convert objects into strings
  • 3. Deserialization: Restore object from string
  • Appendix: Command and option parameter analysis
    • F.1 ConvertTo-Json command
    • F.2 ConvertFrom-Json command
      • Example
        • Example 1: Convert DateTime object to JSON object
        • Example 2: Get JSON string from web service and convert to PowerShell object
        • Example 3: Convert JSON string to custom object
        • Example 4: Convert JSON string to hash table
        • Example 5: Round tripping a JSON string containing a single element array
      • parameter
      • input and output

1. Overview

In PowerShell, the serialization and deserialization of an object is to convert the object into a string The process of formattingfor storage or transmission and then restoring from a string to an object. This is useful in many applications, especially when you need to save objects to a file, pass them to a remote server, or store them in a database.

The rest of this article will describe how to perform the serialization and deserialization operations of objects in PowerShell.

2. Serialization: convert objects into strings

To serialize an object into a string, you can use the ConvertTo-Json cmdlet in PowerShell. Here is an example showing how to serialize an object into a JSON string:

# Create a sample object

$person = @{<!-- -->
    FirstName = "Jack"
    LastName = "Lee"
    Age=29
}

# Serialize object to JSON string

$jsonString = $person | ConvertTo-Json
# Print JSON string
Write-Host "JSON string:"
Write-Host $jsonString

The result of running the output is:

JSON string:
{
    "Age": 29,
    "FirstName": "Jack",
    "LastName": "Lee"
}

In the example above, we first create a sample object $person and then use ConvertTo-Json to convert it to a JSON string. You can use this string to save the object to a file or pass it elsewhere.

3. Deserialization: Restore object from string

To restore an object from a string, you can use the ConvertFrom-Json cmdlet. Here’s an example of how to restore an object from a JSON string:

# JSON string
$jsonString = '{
    "FirstName": "Jack",
    "LastName": "Lee",
    "Age": 28
}'

# Restore object from JSON string
$person = $jsonString | ConvertFrom-Json

#Print the restored object
Write-Host "Restored object:"
Write-Host "FirstName: $($person.FirstName)"
Write-Host "LastName: $($person.LastName)"
Write-Host "Age: $($person.Age)"

The result of running the output is:

The restored object:
FirstName: Jack
LastName: Lee
Age: 28

In the example above, we first have a JSON string $jsonString and then use ConvertFrom-Json to restore it to an object. The restored object can access its properties like a normal object.

Note: The object’s properties and structure must be consistent with the JSON representation of the original object, otherwise deserialization may fail.

Serialization and deserialization make it easy to save, transfer, and restore objects in PowerShell, which is useful for many application scenarios. Whether interacting with file systems, network communications, or databases, object serialization and deserialization are powerful tools.

Appendix: Command and option parameter analysis

F.1 ConvertTo-Json command

A string used to convert an object to JSON format. It allows you to serialize PowerShell objects into JSON format for easy storage, transmission, and data interaction with other systems. The format of this command is:

ConvertTo-Json [-InputObject] <PSObject> [-Depth <int>] [-Compress] [-EscapeHandling <String>] [-Pretty] [<CommonParameters>]

in:
-InputObject: This is a required parameter that specifies the PowerShell object to be converted to JSON. Can be a scalar value, array, hash table, custom object, etc.

-Depth: Used to specify the nesting depth of JSON objects. By default, the depth is 2, which means that up to two levels of nested objects are converted. If your object has more levels of nesting, you can handle this by specifying a greater depth. But be aware that setting the depth too high may result in the generated JSON data being very complex.

-Compress: If this option is specified, the generated JSON string will not contain extra spaces and indentation, making it more compact. This is useful for reducing the size of JSON data.

-EscapeHandling: Used to specify how to handle escape characters when generating JSON strings. Optional values include:

  • Default: Use the default escape processing method.
  • EscapeHtml: Escape HTML characters.
  • EscapeNonAscii: Escape non-ASCII characters.
# Define a complex PowerShell hash table object
$complexObject = @{<!-- -->
    Name = "Jack"
    Info = @{<!-- -->
        Age=29
        Address = @{<!-- -->
            Street = "Xuefu Road, Nanshan District"
            City = "Shenzhen"
        }
    }
}

# Convert object to JSON string, set depth to 4
$jsonString = $complexObject | ConvertTo-Json -Depth 4

# Print JSON string to console
Write-Host "Generated JSON string content:"
Write-Host $jsonString

The running result is:

Generated JSON string content:
{
    "Name": "Jack",
    "Info": {
                 "Age": 29,
                 "Address": {
                                 "City": "Shenzhen",
                                 "Street": "Xuefu Road, Nanshan District"
                             }
             }
}

F.2 ConvertFrom-Json command

Reference: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.3

ConvertFrom-Json is used to convert JSON-formatted strings into custom objects or hash tables. JSON is a data exchange format commonly used on websites. This command can help you convert these JSON-formatted data into objects that are easy to operate in PowerShell.

The syntax format of this command is:

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

in:

  • -InputObject: Specifies the JSON string to be converted to a JSON object.
  • -AsHashtable: Convert JSON to a hash table object. Starting in PowerShell 7.3, this object is an OrderedHashtable and preserves the ordering of the keys in the JSON.
  • -Depth: Set the maximum depth allowed for JSON input, the default is 1024.
  • -NoEnumerate: Specifies not to enumerate the output, used to ensure that JSON round-trips can be made through ConvertTo-Json.

The ConvertFrom-Json cmdlet converts a JSON-formatted string into a custom PSObject or hash table object, where each field corresponds to an attribute in the JSON string. JSON is often used on websites to represent object data in text form. This cmdlet adds properties to a new object as it processes each line of the JSON string.

The JSON standard allows duplicate key names, but not in PSObject and Hashtable types. For example, if the JSON string contains duplicate keys, this cmdlet will only use the last key. See additional examples below.

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

Example

Example 1: Convert DateTime object to JSON object

The following command uses the ConvertTo-Json and ConvertFrom-Json cmdlets to convert the DateTime object obtained from the Get-Date cmdlet to a JSON object and then convert it again is PSCustomObject.

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

This example uses the Select-Object cmdlet to obtain all properties of a DateTime object. It uses the ConvertTo-Json cmdlet to convert the DateTime object to a JSON-formatted string, and then uses the ConvertFrom-Json cmdlet to convert the JSON-formatted string to a PSCustomObject object.

Example 2: Get a JSON string from a web service and convert it to a PowerShell object

The following command uses the Invoke-WebRequest cmdlet to get a JSON string from a web service, and then uses the ConvertFrom-Json cmdlet to convert the JSON content into an object that can be managed in PowerShell.

# Ensure 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 will automatically convert the JSON content into objects.

Example 3: Convert JSON string to custom object

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

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

This command uses the Get-Content cmdlet to get the string in the JSON file. Use the -Raw parameter to return the entire file as a single JSON object, then use the pipe operator to send the delimited string to the ConvertFrom-Json cmdlet to convert it to a custom object .

Example 4: Convert JSON string to hash table

This example shows an example of using the -AsHashtable switch to overcome some of the limitations of the ConvertFrom-Json command.

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

The JSON string contains two key-value pairs, and the keys only differ in case. Without the switch, this command will report an error.

Example 5: Round trip to a JSON string containing a single element array

This example shows how to use the -NoEnumerate switch to round-trip a JSON array containing a single element.

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

A JSON string contains an array containing a single element. Without the switch, converting JSON to PSObject and then converting back using the ConvertTo-Json command will result in a single integer.

Parameters

  • -AsHashtable: Convert JSON to a hash table object.
  • -Depth: The maximum depth allowed for JSON input.
  • -InputObject: JSON string to be converted to a JSON object.
  • -NoEnumerate: Specifies that the output should not be enumerated.

Input and output

  • Input: JSON string.
  • Output: PSCustomObject (custom object) or OrderedHashtable (ordered hash table).

Notice

  • This cmdlet is implemented using Newtonsoft Json.NET.
  • Starting with PowerShell 6, ConvertTo-Json will attempt to convert a string formatted as a timestamp to a DateTime value.
  • The PSObject type will keep the order of the properties the same as in the JSON string. Starting from PowerShell 7.3, the AsHashtable parameter will create an OrderedHashtable. The key-value pairs are added in the order in the JSON string, and the ordered hash table will maintain this order.