Skip to content

Instantly share code, notes, and snippets.

@wopfel
Created September 28, 2019 15:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wopfel/47ecba14b4f17a1337d7484ae4819fc4 to your computer and use it in GitHub Desktop.
Save wopfel/47ecba14b4f17a1337d7484ae4819fc4 to your computer and use it in GitHub Desktop.
Read a .js file from STDIN and write JSON-compatible output (suitable for jq)
#!/bin/perl
# Description:
# Read a .js file from STDIN and write JSON-compatible output (suitable for jq)
# The input file in the format ...
# var data = { "run": [...
# cannot be read by jq directly. This script transforms a javascript file to json output.
use strict;
use warnings;
$| = 0;
my $level = 0;
my $delim = "";
while ( <> ) {
# Remove var xxx = from js
s/^\s*var
\s*
\S+
\s*=\s
//x;
my $round = 0;
while ( length > 0 ) {
# { and }
if ( s/^\{\s*// ) {
print $delim; $delim = "";
print " " x (2*$level);
print "{";
print "\n";
$level++;
}
if ( s/^\}\s*(,?)\s*// ) {
$level--;
print "}";
$delim = $1;
}
# [ and ]
if ( s/^\[\s*// ) {
print $delim; $delim = "";
print " " x (2*$level);
print "[";
print "\n";
$level++;
}
if ( s/^\]\s*(,?)\s*// ) {
$level--;
print "]";
$delim = $1;
}
# "bla": ...
if ( s/^("[^"]+")\s*:\s*//i ) {
print $delim; $delim = "";
print "\n";
print " " x (2*$level);
print "$1: ";
}
# "data",
if ( s/^("[^"]*")\s*(,?)\s*//i ) {
print $delim; $delim = "";
print "$1";
$delim = $2;
}
# 'data',
if ( s/^'([^']*)'\s*(,)\s*//i ) {
print $delim; $delim = "";
my $text = $1;
$delim = $2;
$text =~ s/"/\\"/g; # Replace " by \"
print "\"$text\"";
}
# number data
if ( s/^([0-9.]+)\s*(,?)\s*//i ) {
print $delim; $delim = "";
print "$1";
$delim = $2;
}
# Terminates program if there seems to be an endless loop
# Maybe a problem with very long lines
$round++;
#print $round;
die if $round > 99990;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment