Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk: Formatting output as json [duplicate]

Tags:

bash

awk

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?

like image 465
devang Avatar asked Jun 06 '13 21:06

devang


1 Answers

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.

like image 75
glenn jackman Avatar answered Sep 21 '22 20:09

glenn jackman