Created
November 3, 2024 12:59
-
-
Save Ozymandias42/2054d8e19324fc56336f6492553ff240 to your computer and use it in GitHub Desktop.
printenv to JSON parser in AWK
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BEGIN { | |
printf("{") ; #Start with Newline, then Open JSON Object with '{' | |
FS="="; #Field Separator - Field: VARNAME=VALUE | |
#RS="\0"; #Record Separator - Record: VARNAME=VALUE \0 VARNAME2=VALUE2 | |
} | |
{ | |
#This part writes the "KEY": part | |
switch(NR) { #Also using sprintf everywhere for better escaping | |
case 1 : printf("\n%s: ",sprintf("\"%s\"",$1)); break; #For the first line | |
default: printf(",\n%s: ",sprintf("\"%s\"",$1)); break; #Start any other line with ',' | |
} | |
#This prt writes the [ "val1", "val2", ..., "valN" ] part | |
valuestr=$2; | |
split(valuestr,value_arr,":"); | |
printf("[ "); | |
for (i in value_arr) { | |
nextval=i+1; | |
#Substitutions to get rid of problematic control-characters | |
value_arr[i]=gensub("x1b","\\\\x1b","g",value_arr[i]); | |
value_arr[i]=gensub("x2d","\\\\x2d","g",value_arr[i]); | |
printf("%s", sprintf("\"%s\"",value_arr[i])); | |
if(value_arr[nextval] == "" && value_arr[(nextval+1)] != ""){ | |
printf("::%s",sprintf("\"%s\"",value_arr[(nextval+1)])); break; #FIX for single values of form foo::bar | |
} | |
#else | |
# printf(""); | |
if(value_arr[nextval] != ""){ | |
printf(","); | |
} | |
} | |
printf(" ]"); | |
} | |
END { | |
printf"\n}"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment