简体   繁体   中英

making array of hashes from file text perl

I have a text file which looks like this

{
  "TYPE": "EMAIL",
  "ITEMS": [
    {
      "SENT": "2016-02-01T19:03:02.00Z",
      "SUBJECT": "UPCOMING EVENTS: ORIENTATION 2016",
      "TIMEZONE": "AUSTRALIA/MELBOURNE",
      "CONTENT": "WE'RE PLEASED TO BE WORKING WITH RMIT LINK'S ORIENTATION TEAM AND RUSU TO WELCOME ALL NEW STUDENTS TO CAMPUS THROUGH A SERIES OF EXCITING ORIENTATION EVENTS. THIS EMAIL SERVES AS A NOTIFICATION TO MAKE SURE YOU KNOW WHEN THE MAJOR EVENTS ARE OCCURRING, TO ENSURE THEY DON'T INTERRUPT YOUR WORK AND SO THAT YOU ARE ABLE TO ENCOURAGE ALL NEW STUDENTS TO ATTEND. BRUNSWICK ALL STUDENTS WELCOME, 23 FEBRUARY 12 - 1:30PM BRUNSWICK COURTYARD. BUNDOORA ALL STUDENTS WELCOME, 24 FEBRUARY 12 - 2PM BUNDOORA WEST CONCOURSE. CITY ALL STUDENTS WELCOME, 25 FEBRUARY 11AM - 2:30PM ALUMNI COURTYARD, UNIVERSITY WAY. RUSU WELCOME BASH, 25 FEBRUARY 4PM - 9PM ALUMNI COURTYARD. CITY CLUBS DAY, 3 MARCH 11AM - 2PM ALUMNI COURTYARD, UNIVERSITY WAY."
    },
    {
      "SENT": "2016-03-03T19:03:02.00Z",
      "SUBJECT": "PROJECT 1 FIRST TIME MEETING",
      "TIMEZONE": "AUSTRALIA/MELBOURNE",
      "CONTENT": "EARLY NEXT WEEK IS GOOD FOR US.  HOW ABOUT MONDAY 11AM?"
    },
    {
      "SENT": "2016-03-03T19:03:02.00Z",
      "SUBJECT": "PROJECT 1 FIRST TIME MEETING",
      "TIMEZONE": "AUSTRALIA/MELBOURNE",
      "CONTENT": "EARLY NEXT WEEK IS GOOD FOR US.  HOW ABOUT TUESDAY 11:30 AM?"
    },
}

I'm trying to extract the information making ITEMS as an array of Hashes. So that i can access the values for sent subject timezone and etc.

I have tried this it doesnt work. Any help?

my @AoH ;



while ( <> ) {
    my $rec = {};
    for  my $field ( split ) {
        (my $key, my $value) = split /:/, $field;
        $rec->{$key} = $value;
    }
    push @AoH, $rec;
}

That's JSON data ( JavaScript Object Notation ) except that the very last comma , should be a closing square bracket ] . Use the JSON module to decode it into a Perl data structure

This program shows the principle. It prints just the subject line of each item, but I think you get the idea

use strict;
use warnings 'all';

use JSON qw/ decode_json /;

my $json = do {
    open my $fh, '<:raw', 'text_file.txt' or die $!;
    local $/;
    <$fh>;
};

my $data = decode_json($json);
my $items = $data->{ITEMS};

for my $item ( @$items ) {
    print $item->{SUBJECT}, "\n";
}

output

UPCOMING EVENTS: ORIENTATION 2016
PROJECT 1 FIRST TIME MEETING
PROJECT 1 FIRST TIME MEETING

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM