#!/usr/bin/env awk
#
# Converts the output to JSON.
#
# The first record is used as column names.
#
# Dependencies:
#   - None
#
# Examples:
#   - tawk 'json()' file.txt
#   - tawk 'json(tuple5())' file.txt
#   - tawk 'json($srcIP4 FS $dstIP4)' file.txt
#   - tawk 'aggr(tuple2())' file.txt | tawk 'json($0)'

@include "isnum"
@include "unquote"

function json(s,        _f, _i, _l, _str, _val) {
    if (!__JSONCOLNAME__[1]) {
        if (length() == 0) next
        split(s ? s : $0, __JSONCOLNAME__, FS)
        gsub("^" __HDRSEP__, "", __JSONCOLNAME__[1]) # remove leading character, e.g., percent
        print "["
        next
    } else {
        _l = split(s ? s : $0, _f, FS)
        if (_l == 0) next
        if (__JSON_NR__ > 0) {
            print ","
        }
        __JSON_NR__++
        _str = "{" # start of JSON object
        for (_i = 1; _i <= _l; _i++) {
            # Print numbers as such
            if (isnum(_f[_i])) _val = _f[_i]
            # Print string without inner quotes as such
            else if (_f[_i] ~ /^"[^"]*"$/) _val = _f[_i]
            # Escape strings with inner quotes
            else if (unquote(_f[_i]) ~ /"/) {
                _val = _f[_i]
                gsub(/\\/, "\\\\", _val) # escape backslash
                gsub(/"/, "\\\"", _val)  # escape quotes
                _val = "\"" _val "\""
            }
            # Surround other values with quotes
            else _val = "\"" _f[_i] "\""
            _str = _str " \"" __JSONCOLNAME__[_i] "\": " _val ","
        }
        gsub(/,$/, "", _str) # discard trailing comma
        printf "%s }", _str  # end of JSON object
    }
}

END {
    if (__JSONCOLNAME__[1] > 0) {
        print "\n]"
    }
}
