Convert Key=Value Pair into JSON with AWK - Shell | Devops Junction

How to convert a key-value pair into JSON.  While there are many ways to programmatically do it. I often find myself doing this type of conversion quite often and I looked out for a simple solution.

What can be simpler than having it done with the built-in tools of your Linux/mac like awk

So here is the quick snippet to converts the key=value pairs into a JSON format

key value to json

As you know JSON enquotes the key and value in doublequotes  so which has also been addressed part of this.

So let us consider a sample key-value data given below.

username=sarav
secret=YouOweMeaBeer
address=virtualspaceovertheweb
website=gritfy.com
about=aspirer
[email protected]
skills=['daydreaming','writing','music']

 

I have saved this content into a file named test.env and converting it now to the JSON with the following command

This is the Shell script with awk to convert key value pair into JSON

#!/bin/bash
# sarav ([email protected])
# convert key=value to json
# Created at Gritfy ( Devops Junction )
#

file_name=$1
last_line=$(wc -l < $file_name)
current_line=0

echo "{"
while read line
do
  current_line=$(($current_line + 1))
  if [[ $current_line -ne $last_line ]]; then
  [ -z "$line" ] && continue
     echo $line|awk -F'='  '{ print " \""$1"\" : \""$2"\","}'|grep -iv '\"#'
  else
    echo $line|awk -F'='  '{ print " \""$1"\" : \""$2"\""}'|grep -iv '\"#'
  fi
done < $file_name
echo "}"

 

Just copy and paste the snippet given above into a file with .sh extension

give executable permission to the script

chmod a+x /tmp/keytojson.sh

then execute the script with the file name where you have the key=value data

keytojson.sh /tmp/test.env

you would be presented with the fully constructed JSON like this

without having to use the script all the time. There is an easy way.

Add following the content to your user profile file  ~/.zshrc or ~/bashrc

function keytojson {
    file_name=$1
    last_line=$(wc -l < $file_name)
    current_line=0
    echo "{"
    while read line
    do
    current_line=$(($current_line + 1))
    if [[ $current_line -ne $last_line ]]; then
    [ -z "$line" ] && continue
        echo $line|awk -F'='  '{ print " \""$1"\" : \""$2"\","}'|grep -iv '\"#'
    else
        echo $line|awk -F'='  '{ print " \""$1"\" : \""$2"\""}'|grep -iv '\"#'
    fi
    done < $file_name
    echo "}"
}

Now you can simply use keytojson it without having to remember the location of the script. Just like any other Linux command

See it in use.

This keytojson is mostly useful in converting .env files to JSON format. so we can call this envtojson as well.

If you are looking for Automations like this as a service. Try us

Cheers
Sarav AK

Follow me on Linkedin My Profile
Follow DevopsJunction onFacebook orTwitter
For more practical videos and tutorials. Subscribe to our channel

Buy Me a Coffee at ko-fi.com

Signup for Exclusive "Subscriber-only" Content

Loading