2017-08-27 88 views
-2

我想知道如何使用Perl以Json格式存储文本文本。从文本文件如何使用Perl以json格式存储文本文本

文本

23rd Street Wave the Wheat Ale 

Lawrence, Kansas, USA 

5.2 

13.65 

Rating - 0.00 

3 Guys & A Beer’d Wheat the People 

Carbondale, Pennsylvania, USA 

5.2 

Unknown 

Rating - 0.00 

51 North Paint Creek Wheat 

Lake Orion, Michigan, USA 

4.8 

Unknown 

Rating - 0.00 

我曾试图执行代码,但它失败了,因为我发现,Perl可以使用,而在互联网上循环读取文件。

下面是我的Perl脚本

for($i = 0; $i < $fileSize; $i+2){ 
say qq{{"beerName": "$beerName", 
"location":"$location", 
"ABV":"$ABV", 
"IBU":"$IBU", 
"Rating":"$Rating"}}; 
} 
+2

使用模块[JSON](http://search.cpan.org/~ishigaki/JSON-2.94/lib/JSON.pm) – zdim

+3

“失败”是什么意思?当你运行你的程序时会发生什么?你预期会发生什么?发表一个https://stackoverflow.com/help/mcve – Robert

+0

我很困惑...你要求帮助存储数据,但是你显示一个文本文件而不是数据结构?! – ikegami

回答

1

不知道你的文本文件的结构是什么,以及如何一致的是。我认为每个条目都是5行,每个条目的顺序相同。如果是这种情况,可能有一种方法是一次读取5行文本文件,将每行分配给相应的散列键,然后将该散列值存储在一个数组中,稍后我们可以使用该数组作为JSON结构体。也许一个更优雅的方式做到这一点,但对于这样的事情:

#!/usr/bin/perl 
use strict; 
use warnings; 
use autodie; 

use JSON; 

my $input_file = shift; 
my @results; 

open(my $fh, "<", $input_file); 
# Read the text file 5 lines at a time, and store each line in the hash data with the desired keys. 
while ((my @lines) = map { scalar(<$fh>) or() } 0..4) { 
    my %data = ('beername' => $lines[0], 
       'location' => $lines[1], 
       'ABV'  => $lines[2], 
       'IBU'  => $lines[3], 
       'Rating' => $lines[4], 
    ); 
    # Store these hash refs in an array that we'll later convert to JSON. 
    push(@results, \%data); 
} 

# Write results to file. 
open(my $json_out, ">", 'beers.json'); 
print {$json_out} encode_json(\@results); 

这将导致“beers.json”文件,该文件将具有以下结构:

$ json_xs <beers.json 
[ 
    { 
     "ABV" : "5.2\n", 
     "IBU" : "13.65\n", 
     "location" : "Lawrence, Kansas, USA\n", 
     "Rating" : "Rating - 0.00\n", 
     "beername" : "23rd Street Wave the Wheat Ale\n" 
    }, 
    { 
     "ABV" : "5.2\n", 
     "IBU" : "Unknown\n", 
     "location" : "Carbondale, Pennsylvania, USA\n", 
     "Rating" : "Rating - 0.00\n", 
     "beername" : "3 Guys & A Beerââ¬â¢d Wheat the People\n" 
    }, 
    { 
     "location" : "Lake Orion, Michigan, USA\n", 
     "Rating" : "Rating - 0.00\n", 
     "beername" : "51 North Paint Creek Wheat\n", 
     "IBU" : "Unknown\n", 
     "ABV" : "4.8\n" 
    } 
] 

就像我说的,可能不够高雅,完全依赖于每个啤酒的文件长度为5行,每个啤酒的元数据每次都是相同的顺序。但是,如果没有别的办法,这可能是一个很好的起点?

+0

Thx,这就是我想要的,对那些试图解决这个问题的人感到抱歉,我会在提问时提高自己。 – ZiSean