Skip to content

Instantly share code, notes, and snippets.

@justjkk
Created May 9, 2010 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save justjkk/395304 to your computer and use it in GitHub Desktop.
Save justjkk/395304 to your computer and use it in GitHub Desktop.
pretty-format json file using lex
/* 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);
putc('\n',stdout);
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)
{
FILE *fin,*fout;
if(argc>1)
{
fin = fopen(argv[1],"r");
if(!fin)
{
fprintf(stderr,"Could not open %s\n",argv[1]);
exit(0);
}
yyin=fin;
}
if(argc>2)
{
fout = fopen(argv[2],"w");
if(!fout)
{
fprintf(stderr,"Could not write to %s\n",argv[2]);
exit(0);
}
stdout=fout;
}
if(argc>3)
{
fprintf(stderr,"Extra arguments are ignored.");
}
yylex();
putc('\n',stdout);
return 0;
}
int yywrap()
{
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment