No doubt you already use Bash for a wide range of tasks, consequently are already aware it’s purely a procedural scripting language and not object oriented? For the majority of tasks this is fine, however there are times when objects are useful; enter jq, a lightweight and flexible command-line JSON processor.
This post explains how to use jq to convert data into JSON and therefore an object. Say you have a file in /root/ with the content:
hostname=postfix-1 os=Ubuntu1804 location=Digbeth city=Birmingham installed=01-02-2012 active=yes
Now you create a Bash function that will convert the above content into a JSON file. If the file is delimited by a character other than “=” then just change it in the code below:
get_server_details () { jq -R -n '[inputs|split("=")|{(.[0]):.[1]}] | add' /root/serverdetails > /root/serverdetails.json }
Run get_server_details
to do the conversion which will create the JSON file. You can then retrieve specific values, for example you could use the below bit of code to extract the hostname:
cat /root/serverdetails.json | jq -r '."hostname"'
Alternatively use the below bit of code to extract the hostname into a variable:
hname=($(cat /root/serverdetails.json | jq -r '."hostname"'))
The possibilities are endless, certainly this has given enough of an insight to spark your imagination ?
Finally check out my other similar blog post:
Create a PowerShell Object from contents of a file
Be First to Comment