How to Convert YAML to JSON [Python, PowerShell, Go]

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

In order to use data from a server, JSON is more commonly used than XML. This article will show how to convert YAML into JSON using Python, PowerShell and Go.

The “python convert yaml to json one line” is a command-line tool that can be used to convert YAML files into JSON. The tool requires Python, PowerShell, or Go.

How to Convert YAML to JSON [Python, PowerShell, Go]

JSON or YAML files are used to store configuration data in many current technologies, notably in configuration management and Infrastructure as Code (IaC) areas. This tutorial is for you if you need to convert data from YAML to JSON format.

In this post, you’ll learn how to convert YAML data to JSON format using Python, PowerShell, and Go programming.

PowerShell vs. Python: A Clash of Civilizations

Prerequisites

If you want to follow along with the examples in this lesson, make sure you have the following items.

  • An editor for coding. Visual Studio Code version 1.55.1 will be used in this tutorial. You may use whatever coding editor you choose.

A Tutorial on What You Need to Know About Visual Studio Code

  • You’ll need a sample YAML content to get started converting YAML to JSON. Copy the contents of this file into a new operating-systems.yml file. In your working directory, save the YAML file.

operating-systems.yml 100 for Windows 10 Microsoft Windows Server 2019: 50 Microsoft Windows Server 2022: 1 3 (MacOS) 75 CentOS 12th photon

Converting YAML to JSON using Python

Python is a fantastic language for automating tasks. But did you know that you can use Python to convert documents from YAML to JSON? And with just a few simple steps, you’ll be converting YAML to JSON in no time.

This section’s sample needs Python 3.9 and PIP to be installed (the latest version as of this writing is 21.0.1).

Python now has YAML support.

YAML is not supported by Python out of the box. Python, by default, is unable to read or parse YAML documents. To support YAML in Python, you must first install the PyYAML package.

You’ll need to use the pip command, which is the Python package installer, to install the PyYAML module. Follow these instructions to do so.

To begin, open your command interpreter of choice, such as the command prompt or PowerShell. In any case, the pip command should function. PowerShell is used in this example.

Then, in PowerShell, perform the command below. The PyYAML module is installed using this command.

Pip installed the most recent version of PyYAML, as seen in the picture below (5.4.1 as of this writing).

The PyYAML module is installed.The PyYAML module is installed.

Conversion Script Writing

You’re ready to build your conversion script now that you’ve installed the appropriate module (PyYAML). Follow these instructions to construct the YAML to JSON Python script.

1. In your working directory, open your code editor and create a new file named convert-os.py. Your script is included in this file.

2. Paste the code below into your convert-os.py file, which should be blank. This script will read operating-systems.yml’s YAML content, convert it to JSON, then save the JSON result to the python operating-systems.json file.

## convert-os.py ## Import the modules to handle JSON & YAML import yaml import json ## Create a variable to hold the data to import os_list = {} ## Read the YAML file with open(“c:tempoperating-systems.yml”) as infile: # Marshall the YAML into the variable defined above os_list = yaml.load(infile, Loader=yaml.FullLoader) # Print the List to the console. print(os_list) Open a file to write the JSON output. The ‘w’ makes the file writable with open(“c:temppython_operating-systems.json”, ‘w’) as outfile: # Marshall the JSON, setting “indent” makes the file more readable json.dump(os_list, outfile, indent=4) print(“JSON file written.”)

3. Make a backup of the convert-os.py script.

Conversion Script Execution

It’s time to put the conversion script to the test when you’ve finished writing it. To run the YAML to JSON Python script, follow these steps:

1. Start by opening a terminal window. Although PowerShell is used in this essay, the command prompt (CMD) would suffice.

2. Paste the command below into PowerShell and hit Enter. The convert-os.py script you developed in the preceding section is invoked by this command, which executes the Python executable program.

c:tempconvert-os.py python

You should see something like the picture below after executing the program. The program showed the JSON result on the screen and stored it to the c:temppython operating-systems.json file, as you can see.

Using Python to run the YAML to JSON conversion scriptUsing Python to run the YAML to JSON conversion script

3. Finally, open the python operating-systems.json JSON file that was produced by the convert-os.py Python script. To open the file in notepad in this example, perform the PowerShell command below.

C:temppython operating-systems.json in notepad

Using notepad to see the python operating-systems.json fileUsing notepad to see the python operating-systems.json file

Converting YAML to JSON using PowerShell

PowerShell can edit text files and convert objects to a variety of formats, including JSON. Because PowerShell is flexible, you can use the correct module to convert YAML to JSON format.

Support for YAML in PowerShell

JSON content is supported natively by PowerShell, however YAML is not. Fortunately, PowerShell has a module that adds functionality for YAML files. PowerShell-yaml is the name of this module, and the most recent version as of this writing is 0.4.2. To install the module, follow these instructions.

1. Start a PowerShell session on your PC.

2. Paste the command below into PowerShell and hit Enter. The PowerShell-yaml module is installed using the Install-Module cmdlet in this command.

PowerShell-yaml -Install-Module

3. The PowerShell-yaml module will add two new cmdlets to PowerShell after installation. These are the new cmdlets:

The cmdlet ConvertFrom-Yaml converts YAML data to a hash table.

The cmdlet ConvertTo-Yaml converts hash table objects to YAML data.

Run the command below in PowerShell to validate that both cmdlets are accessible.

Get-Command -Module PowerShell-yaml Get-Command -Module PowerShell-yaml Get-Command -Mod

The Get-Command cmdlet displayed the cmdlets from the PowerShell-yaml module, as seen below.

The PowerShell-yaml cmdlets are available for download.The PowerShell-yaml cmdlets are available for download.

Conversion Script Writing

Follow these steps to construct a PowerShell script that converts YAML to JSON.

1. In your working directory, open your code editor and create a new file named convert-os.ps1.

2. Paste the code below into the empty convert-os.ps1 file. The operating-systems.yml file is read and converted to JSON in the code snippet below. It saves the JSON in the PowerShell operating-systems.json file after it has been converted to JSON.

#convert-os.ps1 #Use Get-Content to read the YAML file and ConvertFrom-Yaml to convert the data to a hashtable. The hashtable object is stored in the $os list variable. (Get-Content -Path “C:tempoperating-systems.yml” | ConvertFrom-Yaml) $os list = (Get-Content -Path “C:tempoperating-systems.yml” | ConvertFrom-Yaml) $os list = (Get-Content – #Using ConvertTo-Json, convert the hashtable object in the $os list variable to JSON format. Set-Content -Path “C:tempPowerShell operating-systems.json” Set-Content -Path “C:tempPowerShell operating-systems.json” Set-Content -Path “C:tempPowerShell operating-systems.json” Set-Content -Path “C:tempPowerShell operating-systems.json” Set-Content -Path $os list | ConvertTo-Json) -Value

Get-Content in PowerShell: Reading Text Files Like a Boss

Set-Content: The PowerShell Way to Write to a File is related.

3. Save the convert-os.ps1 file to your computer.

Conversion Script Execution

After you’ve finished writing your conversion script, you’ll need to execute it to convert YAML to JSON. Follow these instructions to run the PowerShell conversion script.

  1. If you haven’t already done so, launch a PowerShell window.

2. Paste the command below into PowerShell and hit Enter. The convert-os.ps1 script you developed in the preceding step is called with this command.

3. Open the JSON output file C:tempPowerShell operating-systems.json that the convert-os.ps1 script produced in the previous step after executing the script. To accomplish so, open the PowerShell operating-systems.json file in notepad using the PowerShell command below.

C:tempPowerShell operating-systems.json in notepad

Viewing the PowerShell operating-systems.json file's contentViewing the PowerShell operating-systems.json file’s content

Converting YAML to JSON using Go

Both Python and PowerShell are high-level programming languages. Being high-level makes screenplay writing simpler, but it also takes away some control. However, since Go is a low-level language, importing YAML data is more difficult.

In this part, we’ll use Go as an example. As of this writing, the most recent version is go1.16.3. If you don’t already have Go installed on your computer, go to the download and install page.

Support for YAML in Go

JSON support is included in Go’s core libraries, much as it is in PowerShell and Python, but YAML is not. To enable YAML functionality in Go, first use the go get command to install the YAML.v3 package. To install the YAML.v3 package, follow these steps:

To begin, open the command shell you wish to use on your computer, such as the command prompt or PowerShell. PowerShell is used in this example.

Then, in PowerShell, copy and execute the command below. The package gopkg.in/yaml.v3 will be downloaded and installed using this command.

In Go, install the yaml.v3 packageIn Go, install the yaml.v3 package

Conversion Script Writing

Follow these steps to make the YAML to JSON conversion Go script.

Create a new file named convert-os in your coding editor. Go to the directory where you’re working.

2. Paste the code below into the empty convert-os.go file. The code imports the necessary packages, creates some memory structures, imports the YAML file, and transforms to JSON before publishing to the c:tempgo operating-systems.json JSON file.

// This tells go which function to load. package main // Import packages: import ( // JSON module “encoding/json” // For writing output to the screen “fmt” // For reading and wiritng files “io/ioutil” // YAML module “gopkg.in/yaml.v3” ) // Define two “Structs” these are data structures in memory, and match // The form of the YAML and JSON files. type operatingSystems struct { Windows10 int yaml:”Windows 10″ WindowsServer2019 int yaml:”Windows Server 2019″ WindowsServer2022 int yaml:”Windows Server 2022″ MacOS int yaml:”MacOS” CentOS int yaml:”CentOS” Photon int yaml:”Photon” } type operatingSystemsjson struct { Windows10 int json:”Windows 10″ WindowsServer2019 int json:”Windows Server 2019″ WindowsServer2022 int json:”Windows Server 2022″ MacOS int json:”MacOS” CentOS int json:”CentOS” Photon int json:”Photon” } func main() { // Let the user know the process has started fmt.Println(“Parsing YAML file”) // Define the path to the input file var fileName string = “c:tempoperating-systems.yml” // Load the YAML from the file. Go requires error handling for this step. yamlFile, err := ioutil.ReadFile(fileName) if err != nil { fmt.Printf(“Error reading YAML file: %sn”, err) return } // Extract the YAML into your Struct var oses operatingSystems yaml.Unmarshal(yamlFile, &oses) //Create the JSON Struct, using the data from the YAML Struct var osesjson = operatingSystemsjson{ Windows10: oses.Windows10, WindowsServer2019: oses.WindowsServer2019, WindowsServer2022: oses.WindowsServer2022, MacOS: oses.MacOS, CentOS: oses.CentOS, Photon: oses.Photon, } // Create a string to output in JSON format. jsonOutput, err := json.Marshal(osesjson) // Print the result to screen. Notice that the %+v means that // the variable name gets printed with the data. This is why // there are no spaces in the output Kay names. fmt.Printf(“Result: %+vn”, osesjson) //write the JSON file err = ioutil.WriteFile(“c:tempGo_operating-systems.json”, jsonOutput, 0644) }

3. Save the convert-os.go file to your computer.

Conversion Script Execution

The go run command is used to execute Go programs, followed by the script’s filename. Follow these steps to execute the YAML to JSON conversion Go script.

1. Open the command shell you wish to use on your computer. The go may be used with either the command prompt or PowerShell on Windows. To execute go in this example, PowerShell is used.

2. Once you’re in PowerShell, duplicate the following command and execute it. This command will execute the c:tempconvert-os.go script using the go run command.

go run the program c:tempconvert-os.go

Convert-os Go script is now running.Convert-os Go script is now running.

3. Open the result file C:tempGo operating-systems.json that the convert-os.go script produced in the previous step after executing the script. This example opens notepad with the Go operating-systems.json file.

In notepad, open the Go operating-systems.json file.In notepad, open the Go operating-systems.json file.

Conclusion

You learnt how to convert YAML data and files to JSON using Python, PowerShell, and Go scripts in this post. Which method do you think you’ll use the most now that you’ve learned how to convert YAML to JSON?

The “convert yaml to json javascript” is a process that can be done in many different programming languages. The most popular ones are Python, PowerShell, and Go.

Frequently Asked Questions

How do I convert YAML to JSON in PowerShell?

A: For converting YAML to JSON in PowerShell, you can use the following command.

Can you convert YAML to JSON?

A: Yes, I can convert YAML to JSON.

How do I convert to JSON in PowerShell?

A: This is an easy task. You can type in ConvertTo-JSON or you could use the following command at your prompt and hit Enter
PS>Hello World! | convertto-json

Related Tags

  • convert yaml to json command line
  • convert yaml to json bash
  • convert yaml to json online
  • convert yaml to json linux
  • convert yaml to json npm

Table of Content