2016-09-15 54 views
-1

我使用的Web服务,在如下JSON格式打印输出,Perl的转换JSON格式为逗号分隔值

{ 
    'message' => '', 
    'data' => [ 
       { 
       'name' => 'Lee calls', 
       'empid' => '1289328', 
       'desc_id' => 'descl23423..23431' 
       }, 
       { 
       'name' => 'Lee calls', 
       'empid' => '23431223', 
       'desc_id' => 'descl23423..234324' 
       } 
      ], 
    'status' => 'success' 
}; 

我只需要“数据”项的值转换成CSV格式。需要的是,我必须创建将在CLI(命令行界面)或Linux终端中执行的perl文件。因此,perl将从Web服务中提取内容,并且必须将JSON输出转换为CSV格式。

你能就此建议我该怎么办?

+2

你有你想如何表示JSON在CSV的想法,这不是JSON – naomik

+4

?没有通用的方法来表示CSV中的嵌套数据结构,您将不得不指定某些内容。如果你更多地解释你的问题的背景可能会有所帮助。 – Borodin

+0

你到目前为止尝试过什么?例如,你看过哪些Perl模块,为什么它们不适合你的任务? –

回答

1

使用JSON将JSON字符串读入Perl数据结构。然后,使用Text::CSV_XS创建CSV格式输出:

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

use JSON; 
use Text::CSV_XS; 

my $json = '[ { 
       "name" : "Lee calls", 
       "empid" : "1289328", 
       "desc_id" : "descl23423..23431" 
       }, 
       { 
       "name" : "Lee calls", 
       "empid" : "23431223", 
       "desc_id" : "descl23423..234324" 
       } ]'; 
my $struct = decode_json($json); 

my $csv = 'Text::CSV_XS'->new({ binary => 1, eol => "\n" }); 
open my $OUT, '>:encoding(UTF-8)', 'output.csv' or die $!; 
$csv->print($OUT, [ @$_{qw{ name empid desc_id }} ]) for @$struct; 
close $OUT or die $!;