I am trying to create a script that will return disk usage for a machine in json format. Here's the command -
df -k $1 | grep -v Filesystem | gawk 'BEGIN { ORS = ""; print " [ "} {printf " { \"name\" : \""$1"\", \"usage\" : \""$5"\", \"mount_point\" : \""$6"\" }" } END { print " ] " }'`
The output obtained is -
[ { "name" : "/dev/sda4", "usage" : "36%", "mount_point" : "/" } { "name" : "udev", "usage" : "1%", "mount_point" : "/dev" } { "name" : "tmpfs", "usage" : "0%", "mount_point" : "/dev/shm" } { "name" : "/dev/sda1", "usage" : "17%", "mount_point" : "/boot" } ]
If you observe, there is a comma missing between two json objects. How to I add this in the command?
df -k $1 | gawk '
BEGIN { ORS = ""; print " [ "}
/Filesystem/ {next}
{ printf "%s{\"name\": \"%s\", \"usage\": \"%s\", \"mount_point\": \"%s\"}",
separator, $1, $5, $6
separator = ", "
}
END { print " ] " }
'
The first time through, the separator variable is empty, then it gets assigned for the second line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With