SSS
SSS

Reputation: 1430

How to convert text file to JSON data in perl?

I have a file name in perl . I want to convert this file to JSON data . Is that possible in perl?

sub conversion {
  my($p)=@_;
  my $f = $p->{file};
  open(FIN,"</pathtofile/$f");
  # now i want to convert this opened file into json 
  # something like encode_json(<FIN>);
  # is that possible?
}

file content sample:

Header   Name Type  Altitude     Depth       
Waypoint 001  User  N12 58.441   E77 32.647                                 
Waypoint 002  User N13 00.503    E77 41.714 
Waypoint 003  User N13 00.856    E77 42.054                             

Upvotes: 0

Views: 3373

Answers (3)

ddoxey
ddoxey

Reputation: 2063

Here's how I'd go about doing that.

#!/usr/bin/perl -Tw

use strict;
use warnings;
use JSON qw( to_json );

my $regex = qr{
    \A
        ( \w+ ) \s+          # Header
        ( \d+ ) \s+          # Name
        ( \w+ ) \s+          # Type
        ( \w+ \s+ \S+ ) \s+  # Altitude
        ( \w+ \s+ \S+ )      # Depth
    \z
}xms;

my @rows;
my @columns = split /\s+/, <DATA>;

while ( my $line = <DATA> ) {

    $line =~ s{(?: \A \s* | \s* \z)}{}xmsg;

    if ( $line =~ $regex ) {

        my %record;

        @record{@columns} = ( $1, $2, $3, $4, $5 );

        push @rows, \%record;
    }
    else {

        warn "malformed input: $line";
    }
}

print to_json( \@rows, { pretty => 1 } );


__DATA__
Header   Name Type  Altitude     Depth
Waypoint 001  User  N12 58.441   E77 32.647
Waypoint 002  User N13 00.503    E77 41.714
Waypoint 003  User N13 00.856    E77 42.054

Upvotes: 6

slayedbylucifer
slayedbylucifer

Reputation: 23492

YOu need to find logic to convert your file into a perl hash and then convert it to json text using "JSON" module from cpan.

Check below code:

#!/usr/bin/perl -w
use strict;
use JSON;

my $hash = { 
            Waypoint    => {
                            Name    => "001",
                            Type    => "User",
                            Altitude    => "58.441",
                            Depth   => "E77 32.647",
                        },
                };

my $json_text = encode_json $hash;
print $json_text."\n";

And its output is:

{"Waypoint":{"Altitude":"58.441","Type":"User","Depth":"E77 32.647","Name":"001"}}

As this question is regarding whether we can convert a txt file (considering the sample provided) into json, I leave it to you to convert your sample file into a hash. However, from above code, it is pretty straight forward to convert a hash into json text

Upvotes: 0

Andy Lester
Andy Lester

Reputation: 93636

You can use the JSON module from CPAN to create JSON from hashes. It's up to you to define the structures you want to JSONify.

Upvotes: 0

Related Questions