Deano
Deano

Reputation: 12200

Print output to JSON format

I have a long output contains a list of items, I'm wondering how I can print it in JASON format.

DLQ_CPP_LTEST
PCA
LTEST_H
ActiveMQ.DLQ
LTEST
DLQ_CPP_NMP_STUDY

Desired output

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

}

I have tried modifying a perl script I have, but I couldn't get the output to show correctly.

#!/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";

Thanks for your help

Upvotes: 1

Views: 360

Answers (1)

Miller
Miller

Reputation: 35208

Build your data structure, and then just use the JSON module:

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

Outputs:

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

Upvotes: 5

Related Questions