-
-
Save yuvipanda/395306 to your computer and use it in GitHub Desktop.
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
// Lex program to pretty-format json file. ***WARNING-Amateurish*** | |
%{ | |
int string=0; | |
int gi=0; | |
void indent(int i); | |
int prev_close=0; | |
%} | |
%% | |
\\\" { //Matching an escaped double quote | |
putc('\\',stdout); | |
putc('"',stdout); | |
prev_close=0; | |
}; | |
\" { //Matching a double quote | |
string=!string; | |
putc(*yytext,stdout); | |
prev_close=0; | |
}; | |
[\{\[\(] { //Matching open type braces | |
if(!string) | |
{ | |
if(prev_close) | |
{ | |
putc('\n',stdout); | |
indent(gi); | |
} | |
putc(*yytext,stdout); | |
putc('\n',stdout); | |
gi++; | |
indent(gi); | |
} | |
else | |
{ | |
putc(*yytext,stdout); | |
} | |
prev_close=0; | |
}; | |
[\}\]\)] { //Matching close type braces | |
if(!string) | |
{ | |
putc('\n',stdout); | |
gi--; | |
indent(gi); | |
putc(*yytext,stdout); | |
} | |
else | |
{ | |
putc(*yytext,stdout); | |
} | |
prev_close=1; | |
}; | |
[,] { //Matching comma | |
if(!string) | |
{ | |
if(prev_close) | |
{ | |
putc('\n',stdout); | |
indent(gi); | |
} | |
putc(*yytext,stdout); | |
printf("\n"); | |
indent(gi); | |
} | |
else | |
{ | |
putc(*yytext,stdout); | |
} | |
prev_close=0; | |
}; | |
[ \t] { //Matching whitespace | |
if(!string) | |
{ | |
//Eat up unwanted whitespace | |
} | |
else | |
{ | |
putc(*yytext,stdout); | |
prev_close=0; | |
} | |
}; | |
[\n] { //Matching New line character | |
//You're not allowed anywhere here. Die... | |
}; | |
. { //Matching any other character | |
if(prev_close) | |
{ | |
putc('\n',stdout); | |
indent(gi); | |
} | |
putc(*yytext,stdout); | |
prev_close=0; | |
}; | |
%% | |
void indent(int i) | |
{ | |
char c = ' '; //Whitespace character to be used for Indenting | |
while(0<i--) | |
{ | |
putc(c,stdout); | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
if(argc>1) | |
{ | |
FILE *file; | |
file = fopen(argv[1],"r"); | |
if(!file) | |
{ | |
printf("Could not open %s\n",argv[1]); | |
exit(0); | |
} | |
yyin=file; | |
} | |
yylex(); | |
printf("\n\n"); | |
return 0; | |
} | |
int yywrap() | |
{ | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment