#!/usr/bin/perl


use File::Path 'make_path';
use JSON::Parse 'json_file_to_perl';
use Data::Dumper;
use strict;
use utf8;

binmode(STDOUT, ":utf8");

# THE LATEST VERSION OF row.json IS AVAILABLE AT https://figshare.com/collections/ROR_Data/4596503

my $inputFile  = '../../../../data/ror.json'; 
my $outputFile = '../../../../data/ror_grid.tsv';

my $data = json_file_to_perl($inputFile);

open(my $OUT, ">$outputFile") or die("Can't open an output file");
binmode($OUT, ":utf8");

foreach my $record (@$data) {
	my $rorId = $record->{'id'};
	my $gridId = '';
	while (my ($type, $v) = each (%{$record->{'external_ids'}})) {
		if ($type eq 'GRID') {
			$gridId = $v->{'all'};
		}
	}
	
	if ($rorId && $gridId) {
		print $OUT $rorId;
		print $OUT "\t";
		print $OUT $gridId;
		print $OUT "\n";
	}
}

close($OUT);

print "\nDone.\n\n";

1;
