Skip to content

Instantly share code, notes, and snippets.

@yuvipanda
Forked from justjkk/json-format.l
Created May 9, 2010 17:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yuvipanda/395306 to your computer and use it in GitHub Desktop.
// 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