A few days back my team member asked, Is there an easy way to convert YAML to JSON and JSON to YAML using scripts? As expected, my answer was: Yes, with PowerShell!

In some scenarios like in configuration management and Infrastructure as Code (IaC) spaces, use JSON or YAML files to store configuration data. This article is for you if you need to convert data from YAML to JSON format. In this article, you will learn ways to convert data YAML to JSON format & JSON to YAML format. To create the YAML to JSON conversion PowerShell script, follow these instructions. This PowerShell module is a thin wrapper on top of YamlDotNet that serializes and un-serializes simple PowerShell objects to and from YAML.

Converting YAML to JSON format:

STEP:1 Get the YAML file path and assign it to Variable

$YAMLFilePath = “C:\dotnet-helper\Build&Release.yml”

STEP:2 Get the YAML Content using Get-Content Cmdlet

$YAMLContent = Get-Content -Path $YAMLFilePath

STEP:3 Convert the YAML file to Hash Value using ConvertFrom-Yaml cmdlet

Read the YAML file using Get-Content and convert the data to a hashtable using ConvertFrom-Yaml (as shown below script).

hash_Value = ($YAMLContent | ConvertFrom-Yaml)

STEP:4 Convert the hashtable object to JSON format using ConvertTo-Json cmdlet & Finally save the file using Set-Content.

Set-Content -Path “C:\dotnet-helper\Build&Release.json” -Value ($hash_Value| ConvertTo-Json)

Full Code:

OUTPUT:

Converting JSON to YAML format:

STEP:1 Get the JSON file path and assign it to Variable

$JsonFilePath = “C:\dotnet-helpers\JSON_Build&Release.JSON”

STEP:2 Get the JSON Content using Get-Content Cmdlet

$JsonContent = Get-Content -Path $JsonFilePath

STEP:3 Convert the JSON file to Hash Value using the ConvertFrom-Json cmdlet

Read the JSON file using Get-Content and convert the data to a hashtable using ConvertFrom-Json (as shown below script).

$hash_Value = ($JsonContent | ConvertFrom-Json)

STEP:4 Convert the hashtable object to YML format using ConvertTo-Yaml cmdlet & Finally save the file using Set-Content.

Set-Content -Path “C:\dotnet-helpers\YML_Build&Release.yml” -Value ($hash_Value| ConvertTo-Yaml)

Full Code:

OUTPUT: