#!/bin/bash

# col2json [-d DFS] {-h} t2-colmn_file .. (or pipe)
# converts a two-column file (1:keyword $DFS 2:keyvalue) to json
# json file is constructed as follows: "{keywords":"keyvalues"}
# keyvalue, if [..], is not quoted either externally or internally

#-----------------------------------------------------------------------
DFS="\t"; HELP=;
#-----------------------------------------------------------------------
TF="OUT_col2json"
trap "[ -e $TF ] && rm $TF" EXIT
#-----------------------------------------------------------------------

while getopts h OPTVAL 
do
    case $OPTVAL in
	d) DFS=$OPTARG;;
        h) HELP=1;;
        *) echo "col2json -h for help"; exit -1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
  echo "col2json [-d DFS] {-h}  2column_file.dlm ... (or pipe)"
  echo "converts two column (keyword $DFS keyvalue) to json structure"
  echo '-d DFS, delimiting character for input table ["\t"]'
  exit
fi

#-----------------------------------------------------------------------
# check to see if data is being supplied by pipe
#-----------------------------------------------------------------------

case $# in
    0) if [ -p /dev/stdin ]; then
          set -- "/dev/stdin"                     #set $1=/dev/stdin
        else
          echo "no file given nor is there a trailing pipe"
          exit -1;
       fi
       cat $1 > $TF; IF=$TF;;
    1) IF=$1;;
    *) echo "can accept only one file"; exit -1;;
esac

#-----------------------------------------------------------------------
# The big lift
#-----------------------------------------------------------------------

awk -F"$DFS" 'BEGIN {q="\""; print "{"}
	      NR==1{
		a1=sprintf("%s%s%s:",q,$1,q) 
                if (index ($2,"["))
		  {a2=sprintf("%s,",$2)}
	        else
	  	  {a2=sprintf("%s%s%s,",q,$2,q)}
	        } 
	      NR!=1{print a1 a2; 
		a1=sprintf("%s%s%s:",q,$1,q) 
                if (index ($2,"["))
		  {a2=sprintf("%s,",$2)}
	        else
	  	  {a2=sprintf("%s%s%s,",q,$2,q)}
                } 
	      END {sub(/,$/,"",a2); print a1 a2; print "}"}' $IF \
| sed 's;\\;&&;g'      #meta-chars for json should be escaped
