Commit 3d845879 authored by Birte Kristina Friesel's avatar Birte Kristina Friesel
Browse files

add csv2json and json2csv helpers for easier station list management

parent 76c660b3
Loading
Loading
Loading
Loading

share/csv2json

0 → 100755
+37 −0
Original line number Diff line number Diff line
#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

use File::Slurp qw(read_file write_file);
use JSON;
use Text::CSV;

my @csv_lines = read_file( 'stations.csv', { binmode => ':utf8' } );
my @stations;
my $csv = Text::CSV->new;

# skip header
shift @csv_lines;

for my $line (@csv_lines) {
	if ( $csv->parse($line) ) {
		my ( $name, $ds100, $uic, $lat, $lon ) = $csv->fields;
		my $station = {
			name    => $name,
			ds100   => $ds100,
			uic     => 0 + $uic,
			latlong => undef
		};
		if ( $lat and $lon ) {
			$station->{latlong} = [ 0 + $lat, 0 + $lon ];
		}
		push( @stations, $station );
	}
}

@stations = sort { $a->{name} cmp $b->{name} } @stations;

my $json_out = JSON->new->utf8->canonical->pretty->encode( [@stations] );
write_file( 'stations.json', $json_out );

share/json2csv

0 → 100755
+30 −0
Original line number Diff line number Diff line
#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

use File::Slurp qw(read_file write_file);
use JSON;
use Text::CSV;

my $json_str = read_file('stations.json');
my $stations = JSON->new->utf8->decode($json_str);
my $csv      = Text::CSV->new( { eol => "\n" } );

my $buf = '';

$csv->combine( 'name', 'DS100', 'UIC (IBNR)', 'Latitude', 'Longitude' );
$buf .= $csv->string;

for my $station ( @{$stations} ) {
	my @fields = ( $station->{name}, $station->{ds100}, $station->{uic} );
	if ( $station->{latlong} ) {
		push( @fields, $station->{latlong}[0], $station->{latlong}[1] );
	}
	if ( $csv->combine(@fields) ) {
		$buf .= $csv->string;
	}
}

write_file( 'stations.csv', { binmode => ':utf8' }, $buf );