summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rwxr-xr-xjson_to_csv.pl86
1 files changed, 86 insertions, 0 deletions
diff --git a/json_to_csv.pl b/json_to_csv.pl
new file mode 100755
index 0000000..23f40b5
--- /dev/null
+++ b/json_to_csv.pl
@@ -0,0 +1,86 @@
+#!/usr/bin/perl -w
+##############################
+#
+# Quick & Dirty Flickr JSON flattening script
+#
+# Author: Solomon Peachy <solomon.peachy@philips.com>
+#
+#############################
+use strict;
+use JSON;
+use utf8;
+
+my $text;
+my $doc;
+
+my @flist;
+my @database;
+my %cols;
+
+binmode STDOUT, ':utf8';
+
+opendir (my $dh, ".") || die;
+while (readdir($dh)) {
+ if (/json/) {
+ push(@flist, $_);
+ }
+}
+
+foreach my $file (@flist) {
+ $text = `cat $file`;
+ $doc = decode_json($text);
+ my %record;
+ foreach my $item (keys(%$doc)) {
+ my $val = $$doc{$item};
+ if (ref($val) eq "HASH") {
+ foreach my $subitem (keys(%$val)) {
+ my $subval = $$val{$subitem};
+ $cols{"$item-$subitem"} = 1;
+ $record{"$item-$subitem"} = $subval;
+# print "$item-$subitem = $subval\n";
+ }
+ } elsif (ref($val) eq "ARRAY") {
+ my $i = 1;
+ foreach (@$val) {
+ my $aval = $$val[$i-1];
+ if (ref($aval) eq "HASH") {
+ foreach my $subitem (keys(%$aval)) {
+ my $subval = $$aval{$subitem};
+ $cols{"$item-$i-$subitem"} = 1;
+ $record{"$item-$i-$subitem"} = $subval;
+# print "$item-$i-$subitem = $subval\n";
+ }
+ } else {
+ $cols{"$item-$i"} = 1;
+ $record{"$item-$i"} = $aval;
+# print "$item-$i = $aval\n";
+ }
+ $i++;
+ }
+ } else {
+ $val =~ tr/\n/ /;
+ $cols{$item} = 1;
+ $record{$item} = $val;
+# print "$item = $val\n";
+ }
+ }
+ push @database, \%record;
+}
+
+#exit(0);
+### DONE, emit output.
+foreach (sort(keys(%cols))) {
+ print "\"$_\",";
+}
+print "\n";
+
+foreach my $row (@database) {
+ foreach (sort(keys(%cols))) {
+ if (defined($$row{$_})) {
+ print "\"$$row{$_}\",";
+ } else {
+ print ",";
+ }
+ }
+ print "\n";
+};