Skip to content

PowerShell: Convert YAML to JSON and JSON to YAML

Last week a friend asked: Is there an easy way to covert YAML to JSON and JSON to YAML without any online-services?
As expected, my answer was: Yes, with PowerShell!

JSON is supported out of the box and there are a few PowerShell Modules that support YAML. My favorite Module is powershell-yaml, a wrapper on top of YamlDotNet.

You can install the powershell-yaml directly from the PowerShell Gallery:

Install-Module -Name powershell-yaml -Force -Repository PSGallery -Scope CurrentUser

Here are some examples to convert back and forth between JSON and YAML:

# Create a YAML Document (Source https://yaml.org/start.html)
$RawYaml = @'
---
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.
'@

# Convert YAML to PowerShell Object
$PsYaml = (ConvertFrom-Yaml -Yaml $RawYaml)

# Convert the Object to JSON
$PsJson = @($PsYaml | ConvertTo-Json)

# Convert JSON back to PowerShell Array
$PsArray = @($PsJson | ConvertFrom-Json)

# Convert the Array to YAML
ConvertTo-Yaml -Data $PsArray

There is also a GIST for it.
Why JSON?
JSON is well known as a serialization format. It is more explicit and more suitable for data interchange between your apis.
I use JSON a lot to store data, where a database is oversized. I also use JSON a lot for configuration files.

Why YAML?
YAML (YAML Ain’t Markup Language) is in my opinion best suited for complex configuration files. And it is much better human-readable for most.

Published inPowerShell

2 Comments

  1. himanshk himanshk

    above cmdlet is not working at last step so adding below info for my main.yml

    applications:
    – name: MY-APP
    -name: Blue-APP
    settings:
    check-interval: 5s
    default-executor: jmeter

    provisioning: local
    #—————————–
    $a=’e:\main.yml’
    $con=(gc $a )-join “`r`n”
    $out=””
    foreach ($i in $con)
    {
    if ($i.indexof(“name: “))
    {
    $substr= $i.replace($i,”$i.xml”)
    }
    else
    {
    $substr= $i
    }
    }
    $out=$out+$substr | out-file $a

    • Joerg Hochwald Joerg Hochwald

      Hi himanshk,

      Did you report the issue to the powershell-yaml author on the PowerShell Gallery?

      Cheers
      Josh

Comments are closed.