JSON Extract, Reformat and Print
Improved slightly over https://news.ycombinator.com/item?id=30916201
sed 's/.\{4\}//' <<eof|flex -8iCrf
/* extract, reformat, print json */
int fileno (FILE *);
#define echo do{if(fwrite(yytext,(size_t)yyleng,1,yyout)){}}while(0)
#define jmp (yy_start) = 1 + 2 *
#define pc(x) putchar(x)
%option nounput noinput noyywrap
%s x1 x2
%%
^\40+
/* quotes
"key":"
"key": "
*/
\"[^\":\]\)]*\":\40*\" echo;jmp x1;
/* bracket followed by brace
"key":[{
"key": [{
*/
\"[^\":\]\)]*\":\40*\[\40*\{ echo;pc(10);
/* number
"key":1
"key": 1
*/
\"[^\":\]\)]*\":\40*[0-9\40\12\15]* echo;jmp x2;
<x2>[,}] pc(10);jmp 0;
/* bracket (unquoted, comma-separated array values)
"key":[
"key": [
*/
\"[^\":\]\)]*\":\40*\[ echo;jmp x1;
/* brace
"key":{
"key": {
*/
\"[^\":\]\)]*\":\40*\{ echo;pc(10);
/* open brace not closed brace */
<x1>[\]\{\"] echo;pc(10);jmp 0;
<x1>[^\]\{\"\12]* echo;
\n|.
%%
int main(){ yylex();exit(0);}
eof
cc -std=c89 -Wall -pedantic -pipe lex.yy.c -static -o yy059
Usage: yy059 < 1.json
yy059 is for extracting JSON from HTML and printing it as a new, left-justified, line-delimited format readable to me.To use with indented JSON, e.g., json_reformat output (json_reformat from yajl project), first remove the indentation, e.g.,
sed 's/ *//' 1.json | yy059
NB. This is made for me, primarily for reading YouTube JSON. It is used in a personal YouTube search utility. JSON from non-YouTube sources, e.g., Twitter, may contain escaped quotes, often for including quotes associated with href tags. Remove escaped quotes first, e.g., using yy064, disclosed here: https://news.ycombinator.com/item?id=30916201