将输出打印为JSON格式

时间:2014-04-10 17:29:11

标签: perl sed awk

我有一个长输出包含一个项目列表,我想知道如何以JASON格式打印它。

DLQ_CPP_LTEST
PCA
LTEST_H
ActiveMQ.DLQ
LTEST
DLQ_CPP_NMP_STUDY

期望的输出

{
 "data":[
  { "{#AMQQ}":"DLQ_CPP_LTEST" },
  { "{#AMQQ}":"PCA" },
  { "{#AMQQ}":"LTEST_H" },
  { "{#AMQQ}":"ActiveMQ.DLQ" }
]

}

我已经尝试修改了我的perl脚本,但是我无法正确显示输出。

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

# Options
my $_proc = "/root/query.txt";

# Validate options
 if ( ! -e $_proc)
{
    die "File $_proc not found!";
}

# Keep count
my $_first = 1;

# Present the data in JSON format
print "{\n";
print "\t\"data\":[\n\n";

# Fetch the data and put it in an array
my @_data = `cat $_proc | awk '{ print \$1 }'`;
chomp @_data;

# Read the array and print the wanted data
 foreach my $_disk (@_data)
{
    # Print the data in JSON
    print "\t,\n" if not $_first;
    $_first = 0;

    print "\t{\n";
    print "\t\t\"{#AMQQ}\":\"$_disk\"\n";
    print "\n\t}\n";
}

print "\n\t]\n";
print "}\n";

感谢您的帮助

1 个答案:

答案 0 :(得分:5)

构建您的数据结构,然后只使用JSON模块:

use strict;
use warnings;

use JSON;

my %hash = (data => [map {chomp; {"{AMQQ}" => $_}} <DATA>]);

print to_json(\%hash);

__DATA__
DLQ_CPP_LTEST
PCA
LTEST_H
ActiveMQ.DLQ
LTEST
DLQ_CPP_NMP_STUDY

输出:

{"data":[{"{AMQQ}":"DLQ_CPP_LTEST"},{"{AMQQ}":"PCA"},{"{AMQQ}":"LTEST_H"},{"{AMQQ}":"ActiveMQ.DLQ"},{"{AMQQ}":"LTEST"},{"{AMQQ}":"DLQ_CPP_NMP_STUDY"}]}